[英]C++ which constructor will be called
If suppose in a class I have two constructors 如果假设在一个类中,我有两个构造函数
Room()
{
length = 0;
width = 0;
}
& 和
Room(int value = 8)
{
length = width = 8;
}
Now if from main I call using: 现在,如果从主要我打电话给:
Room obj1;
obj.display();
which constructor will be called or will it throw error? 哪个构造函数将被调用或将引发错误? I think that it will throw error as compiler will not be able to call the correct constructor because of two same type of constructors present.Is it correct ?
我认为这会引发错误,因为由于存在两种相同类型的构造函数,编译器将无法调用正确的构造函数,对吗?
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
默认构造函数是没有参数的构造函数,或者如果有参数,则所有参数都具有默认值。
In this case code will not compile... You can read more about default constructor from here 在这种情况下,代码将无法编译...您可以从此处阅读有关默认构造函数的更多信息
Assuming that this will be the complete program 假设这将是完整的程序
#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);
}
This code will not compile because of an ambiguous call to the constructor of Room
for the declaration of obj1
. 由于为
obj1
的声明对Room
的构造函数的调用不明确,因此无法编译此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.