当我们为类的对象分配整数值时,为什么会调用参数化构造函数?

Kri*_*ula 1 c++ constructor assignment-operator parameterized-constructor

代码是:

#include<iostream>
using namespace std;

class Integer
{
    int num;

    public:
        Integer()
        {
            num = 0;
            cout<<"1";
        }
        
        Integer(int arg)
        {
            cout<<"2";
            num = arg;
        }
        int getValue()
        {
            cout<<"3";
            return num;
        }

};

int main()
{
    Integer i;
    i = 10;  // calls parameterized constructor why??
    cout<<i.getValue();
    return 0;

}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,语句i=10调用了参数化构造函数。你能解释一下吗。

Sto*_*ica 5

您的参数化构造函数是一个转换构造函数。C++ 非常乐意使表达式有效,只要它可以找到合理的转换序列来使事情起作用。因此,如前所述,10被转换为Integer临时文件,然后由编译器生成的operator= (Integer const&).

如果您希望防止在意外转换中使用构造函数,您可以将其标记为explicit.

explicit Integer(int arg) { /* ... */}
Run Code Online (Sandbox Code Playgroud)

然后它不再是一个转换构造函数,如果没有强制转换(或由您提供的自定义赋值运算符),则无法进行赋值。