具有按引用传递对象的类会出现编译错误
我在单独的头文件中定义了一个 A 类。我希望 B 类拥有对存储为变量的 A 类对象的引用。
像这样:
文件:Ah
class A {
//Header for class A...
};
文件:Bh
#include "A.h"
class B {
private:
(24) A &variableName;
public:
(36) B(A &varName);
};
当我尝试用 g++ 编译它时,出现以下错误:
B.h:24: error: ‘A’ does not name a type
B.h:36: error: expected `)' before ‘&’ token
关于我做错了什么有什么建议吗?如果重要的话,A 类是一个抽象类。
编辑:代码中的一些拼写错误
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
对我来说,它编译得很好(如预期)。我猜
Ah
没有被正确包含。是否有另一个同名文件被包含在内?也许有#ifdef 或其他类似的东西会阻止编译器看到A
的定义。为了检查这一点,我将某种语法错误放入Ah
中,看看编译器是否捕获它。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 ofA
from being seen by the compiler. To check this, I would put some sort of syntax error intoA.h
and see if the compiler catches it.Ah 是否包括 Bh(直接或间接)?如果是这样,那么由于递归包含,您将无法在 B 之前定义 A。如果需要在 A 中定义 B,请使用 前向声明。
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.
您似乎尝试在完全不相关的类 B 中声明类 A 的构造函数,这正是编译器所抱怨的。
如果您希望从编译器的角度使用默认/隐式方式将
B
转换为A
,您将需要类似的东西而不是构造函数声明。
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 anA
from the compiler's perspective, you'll need something likeinstead of a constructor declaration.
据我所知,这段代码是正确的。请检查以下内容:
如果这些都不起作用,那么我无法帮助您,除非您发布发生错误的真实代码。
For all I can see, this code is correct. Check the following please:
If none of these work, well then I cannot help you unless you post the real code where the error happens.
请注意,将引用作为成员变量很少是一个好主意。 B这个名字到底代表什么?
Note that having references as member variables is seldomly a good idea. What does the name B really stand for?