C++中的对象初始化问题头文件
我正在使用 C++ 进行编码,并且类的头文件中有私有数据成员。
private:
Object1 obj1;
Object2 obj2(&obj1);
因此,第二个对象采用指向第一个对象的指针。当我尝试编译该程序时,出现以下错误:
“'&' 之前有预期的标识符” token"
有没有办法在实现文件中实例化此类构造函数内的对象而不是其定义?我该如何纠正这个错误?该程序将无法编译。
I am coding in C++, and I have private data members in the header file of a class.
private:
Object1 obj1;
Object2 obj2(&obj1);
So, the second object takes a pointer to the first object. When I try to compile the program, I get the following error:
"expected identifier before ‘&’ token"
Is there a way to instantiate the objects inside this class' constructor in the implementation file rather than its definition? How do I correct this error? The program won't compile.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++ 中,不能将成员初始化作为类定义的一部分。这种操作应该在构造函数中完成:
这通常会生成一个警告,但只要 obj2 在构造
myClass
已完成。In C++, you cannot initialize members as part of the class definition. This kind of operation should be done in the constructor:
This will usually generate a warning, but will be fine as long as
obj2
does not use its constructor argument until the construction ofmyClass
is complete.编译器通过此错误告诉您的是,您正在尝试创建一个名为
obj2
的方法,返回一个将引用作为参数的Object2
。但它无法弄清楚引用的类型是什么。另一方面,如果您想在构造对象之前设置引用,您可以编写如下内容:
编辑
让你的程序编译并不总是最好的解决方案,也许有一个原因导致它无法编译,你必须理解为什么会这样。仅仅纠正错误可能对您的事业没有帮助。正如 Nawaz 在评论中指出的那样,如果类型
Object1
和Object2
不同,则您尝试做的事情可能不是正确的事情。What your compiler is telling you with this error is that you are trying to make a method called
obj2
, returning anObject2
that is taking a reference as a parameter. But it can't figure out what the type of the reference is.On the other hand if you want to set the reference before the construction of the object you can write something like this :
Edit
Making your program compile is not always the best solution, maybe there is a reason why it won't compile and you have to understand why it is so. Simply correcting the error might not help your cause. As Nawaz pointed out in the comment, if the types
Object1
andObject2
are different, it is possible that what you are trying to do is not the right thing.你不能这样写:
使用构造函数来初始化对象,如下所示:
阅读此内容以详细了解这一点:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
You cannot write like this:
Use constructor to initialize objects, like this:
Read this to understand this in detail:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
您不能像声明中那样向成员分配值。您必须在类的构造函数中执行此操作。
You can't assign values to members like that in their declaration. You'll have to do that in the class' constructor.