1

代码是:

#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;

}

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

4

2 回答 2

5

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

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

explicit Integer(int arg) { /* ... */}

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

于 2021-01-13T08:18:01.637 回答
3

正在调用参数化 ctor,因为Integer创建了临时对象,然后将其分配给您的i对象,例如:

i = Integer(10);

如果您指定赋值运算符,例如:

Integer& operator=(int const val) {
    num = val;
    return *this;
}

不会调用参数化的ctor。

于 2021-01-13T08:07:58.540 回答