【问题标题】:What happens when an object is assigned to a value in c++ [closed]在 c++ 中将对象分配给一个值时会发生什么 [关闭]
【发布时间】:2018-02-13 13:56:14
【问题描述】:

检查以下代码:

#include<iostream>
using namespace std;

class example
{
    public:
    int number;

    example()
    {
        cout<<"1";
        number = 1;
    }

    example(int value)
    {
        cout<<"2";
        number = value;
    }

    int getNumber()
    {
        cout<<"3";
        return number;
    }
};

int main()
{
    example e;
    e = 10;
    cout<<e.getNumber();
    return 0;
}

以上代码的输出是什么。另外,我想知道当一个对象直接赋值给一个值时会发生什么。编译器将如何解释它?

【问题讨论】:

  • "上面代码的输出是什么" - 试过运行吗?
  • 是的,输出是:12310 但我想知道遇到“e = 10”时会发生什么。
  • 学习使用 C++ 不是通过请求 SO 辅导来完成的。 Pick a good book 并遵循。
  • e = 10; 导致调用example(int value) 隐式构造函数,构造example 的临时实例并使用编译器生成的赋值运算符将其分配给e。避免这种行为的一个好习惯是将默认和复制/移动之外的所有构造函数标记为explicit。
  • 使用调试器。 @艾伦理查兹

标签: c++ oop


【解决方案1】:

首先你输入了

example e;

所以调用了第一个构造函数并打印了1

example()
{
    cout<<"1";
    number = 1;
}

输出:

1

然后你输入: e=10 等于 e = example(10); 所以另一个构造函数称为:

example(int value) /// beacause you used example(10)
{
    cout<<"2";
    number = value;
}

所以你的输出是:

12

而number 是2 终于进去了:

cout<<e.getNumber();


3 is couted but in the other hand value is `10`    

因为number = value 你的number 是10
所以最后你的输出是:

12310

感谢@StoryTeller 编辑解释

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-20
    • 2014-09-29
    • 1970-01-01
    • 2012-09-08
    • 2010-12-09
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多