C++在同一行声明多个对象实例时出现问题
对于家庭作业,我很难理解当主类在同一行上实例化同一类的两个对象时的行为,如下所示。请注意,赋值的对象是让类的行为类似于 int:
main () {
MyClass x,y = 5;
cout << "x = " << x << endl; // outputs x = 0...why not 5???
cout << "y = " << y << endl; // outputs y = 5
}
这是头文件类定义:
class MyClass {
public:
MyClass(int initValue = 0); //constructor
operator int() {return myValue}; //conversion operator to int
private:
int myValue;
}
最后是我的源文件:
#include "MyClass.h"
MyClass::MyClass(int initValue) {
myValue = initValue;
}
为什么 x 不像 y 那样用值 5 进行初始化?
For a homework assignment, I'm having a hard time understanding the behavior when the main class is instantiating two objects of the same class on the same line as follows. Note that the object of the assignment is for the class to behave like an int:
main () {
MyClass x,y = 5;
cout << "x = " << x << endl; // outputs x = 0...why not 5???
cout << "y = " << y << endl; // outputs y = 5
}
and here's header file class definition:
class MyClass {
public:
MyClass(int initValue = 0); //constructor
operator int() {return myValue}; //conversion operator to int
private:
int myValue;
}
and finally, my source file:
#include "MyClass.h"
MyClass::MyClass(int initValue) {
myValue = initValue;
}
Why doesn't x get initialized with the value of 5 like y does?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题是 C++ 正在解析
就像您写过的那样
,所以
x
正在默认初始化,而不是用 5 初始化。要解决此问题,请将行更改为读取The problem is that C++ is parsing
As if you had written
And so
x
is getting default-initialized rather than initialized with 5. To fix this, change the line to read