I can see exactly two errors in the code you describe:
Indeed,
x
is not in the scope of
Key::the_key
:
int Key::the_key()const
{
return x;
}
The error message "
Undefined reference to Key::Key(int)
" is related to the following:
class Key
{
public:
Key(int x=0);
};
Constructor Key is declared, but I did not find the body of the constructor anywhere.
Unfortunately, C++ compiler you use does not report such problem when the class is defined; it only reports the problem when the class is used; and the constructor or other function without a body is called. In other words, the compiler allows declarations of (non-virtual) functions without a body when it is statically known they are never called.
As you probably intended, you need to either define a body in you
Key.cpp
or inline it in
Key.h
:
class Key
{
public:
Key(int x=0) { key = x; }
};
By the way, the fact you've use the name
x
for a parameter to be assigned to
key
hints me that this is also a reason for your problem with “
x was not declared in this scope
”. Maybe, you somehow fail to understand that a function paramer scope is limited to this function (or constructor)? If so, how would you imagine it could work?
That's it. Thank you.