![](/img/trans.png)
[英]C++: which is the appropriate constructor to be called: the constructor or the copy constructor?
[英]C++ which constructor will be called
如果假设在一个类中,我有两个构造函数
Room()
{
length = 0;
width = 0;
}
和
Room(int value = 8)
{
length = width = 8;
}
现在,如果从主要我打电话给:
Room obj1;
obj.display();
哪个构造函数将被调用或将引发错误? 我认为这会引发错误,因为由于存在两种相同类型的构造函数,编译器将无法调用正确的构造函数,对吗?
默认构造函数是没有参数的构造函数,或者如果有参数,则所有参数都具有默认值。
在这种情况下,代码将无法编译...您可以从此处阅读有关默认构造函数的更多信息
假设这将是完整的程序
#include <iostream>
struct Room
{
int length;
int width;
Room()
{
length = 0;
width = 0;
}
Room(int value = 8)
{
(void)value;
length = 8;
width = 8;
}
};
int main()
{
Room obj1; // ambiguous call
std::cout << obj1.length << "\n";
return (0);
}
由于为obj1
的声明对Room
的构造函数的调用不明确,因此无法编译此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.