Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当对象被赋值给C++中时,会发生什么?_C++_Oop - Fatal编程技术网

当对象被赋值给C++中时,会发生什么?

当对象被赋值给C++中时,会发生什么?,c++,oop,C++,Oop,检查以下代码: #include<iostream> using namespace std; class example { public: int number; example() { cout<<"1"; number = 1; } example(int value) { cout<<"2"; number = value;

检查以下代码:

#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;
}
以上代码的输出是什么。另外,我想知道当一个对象被直接赋值时会发生什么。编译器将如何解释它?

您首先键入

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

然后你键入: e=10等于e=example10;因此,另一个构造函数称为:

example(int value) /// beacause you used example(10)
{
    cout<<"2";
    number = value;
}
数字是2 最后,在:

cout<<e.getNumber();


3 is couted but in the other hand value is `10`    
用于编辑解释的@StoryTeller的thanx


上面的代码的输出是什么?尝试运行它吗?是的,输出是:12310,但是我想知道当遇到E=10时会发生什么。学习使用C++不是通过请求这样做来完成的。然后,e=10;导致调用exampleint值隐式构造函数来构造example的临时实例,并使用编译器生成的赋值运算符将其赋值给e。避免这种行为的一个很好的做法是将默认值和复制/移动之外的所有构造函数标记为显式。使用调试器@AllenRichards
example(int value) /// beacause you used example(10)
{
    cout<<"2";
    number = value;
}
12
cout<<e.getNumber();


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