Class with pass-by-reference object gives compile error
I've got a class A defined in a separate header file. I want class B to have a reference to a object of class A stored as a variable.
Like this:
File: A.h
开发者_开发问答class A {
//Header for class A...
};
File: B.h
#include "A.h"
class B {
private:
(24) A &variableName;
public:
(36) B(A &varName);
};
When i try to compile it with g++ I get the following error:
B.h:24: error: ‘A’ does not name a type
B.h:36: error: expected `)' before ‘&’ token
Any suggestions on what I'm doing wrong? If it matters, the class A is an abstract class.
EDIT: Some typos in the code
By me it compiles fine (as expected). I'm guessing A.h
isn't being included properly. Is there another file with the same name that gets included instead? Perhaps there are #ifdef
s or some such that prevent the definition of A
from being seen by the compiler. To check this, I would put some sort of syntax error into A.h
and see if the compiler catches it.
Does A.h include B.h (directly or indirectly)? If so, then you wouldn't be able to define A before B because of the recursive inclusions. If B needs to be defined in A, use a forward declaration.
You appear to try and declare a constructor for class A inside a completely unrelated class B, which is what the compiler is complaining about.
If you want to have default/implicit way of turning a B
into an A
from the compiler's perspective, you'll need something like
operator A(B const &var);
instead of a constructor declaration.
For all I can see, this code is correct. Check the following please:
- is A in some namespace?
- is A a nested class?
- is A the name of some macro in your code?
- is A really named A, or is there some typo in your real code?
If none of these work, well then I cannot help you unless you post the real code where the error happens.
Note that having references as member variables is seldomly a good idea. What does the name B really stand for?
精彩评论