我正在学习c++。我做了这个程序,但在编译时,程序显示出了惊人的错误。我不明白,如果我正在创建一个没有参数的对象,那么它应该只调用默认构造函数&程序运行时应该没有任何错误。这是代码:
#include<iostream>
using namespace std;
class room
{
int length,width;
public:
room()
{
cout<<"Default constructor";
}
room(int l=0)
{
cout<<"Constructor"; //the compiler is taking this also as default constructor
}
room(int l=0,int w=0)
{
cout<<"Constructor"; //the compiler is taking this also as default constructor on making other two as comment
}
};
int main()
{
room r1;
return 0;
}
我在Codeblocks、Dev c++&GCC。
room r1
不明确,因为具有所有默认参数的构造函数已经可用作为默认构造函数的room()
§12.1
类X的默认构造函数是类X的构造函数可以在没有参数的情况下调用。如果没有用户声明类X的构造函数,一个没有参数的构造函数是隐式声明为默认(8.4)。
您有3个构造函数,可以在不提供任何参数的情况下调用。因此编译器被这3个构造函数弄糊涂了。