提问人:Krishna Kanth Yenumula 提问时间:1/13/2021 最后编辑:Nicol BolasKrishna Kanth Yenumula 更新时间:10/2/2022 访问量:237
当我们将整数值分配给类的对象时,为什么调用参数化构造函数?
Why is parameterized constructor called, when we assign an integer value to an object of a class?
问:
代码为:
#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
答:
3赞
NutCracker
1/13/2021
#1
之所以调用参数化 ctor,是因为创建了临时对象,然后将其分配给您的对象,例如:Integer
i
i = Integer(10);
如果指定赋值运算符,例如:
Integer& operator=(int const val) {
num = val;
return *this;
}
不会调用参数化 CTOR。
5赞
StoryTeller - Unslander Monica
1/13/2021
#2
参数化构造函数是转换构造函数。C++ 非常乐意使表达式有效,只要它能找到一个合理的转换序列来使事情正常工作。因此,如前所述,被转换为临时的,然后由生成的编译器分配。10
Integer
operator= (Integer const&)
如果希望防止构造函数在意外转换中使用,可以将其标记为 。explicit
explicit Integer(int arg) { /* ... */}
然后,它不再是转换构造函数,如果没有强制转换(或自定义赋值运算符,由您提供),则无法进行赋值。
评论
0赞
U. W.
1/13/2021
这就是为什么您应该将所有具有一个参数的构造函数声明为显式的主要原因。
评论
10
是用于初始化 的临时对象。你现在所拥有的是,因为你在班级中缺少赋值运算符。i
i = Integer(10)