C++在同一行声明多个对象实例时出现问题

发布于 2024-10-21 00:49:51 字数 654 浏览 0 评论 0原文

对于家庭作业,我很难理解当主类在同一行上实例化同一类的两个对象时的行为,如下所示。请注意,赋值的对象是让类的行为类似于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

断念 2024-10-28 00:49:51

问题是 C++ 正在解析

MyClass x,y = 5;

就像您写过的那样

MyClass x;
MyClass y = 5;

,所以 x 正在默认初始化,而不是用 5 初始化。要解决此问题,请将行更改为读取

MyClass x = 5, y = 5;

The problem is that C++ is parsing

MyClass x,y = 5;

As if you had written

MyClass x;
MyClass y = 5;

And so x is getting default-initialized rather than initialized with 5. To fix this, change the line to read

MyClass x = 5, y = 5;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文