关于C++重载构造函数的问题,求助~

来源:百度知道 编辑:UC知道 时间:2024/04/30 14:08:14
#include <iostream>
using namespace std;

class rectangle
{
public: rectangle();
rectangle(int,int);
private: int itslenth;
int itswidth;
};

rectangle::rectangle()
{cout<<"The first function is called "<<endl;}

rectangle::rectangle(int lenth,int width)
{cout<<"The second function is called,the lenth is "<<lenth<<",the width is "<<width<<endl;}

void main()
{
rectangle rect1();
rectangle rect2(4,3);
}

上面这个程序,运行后为什么第一个rect1的构造函数不被调用呢???

rectangle rect1();
一句中,编辑器会认为有参数传递,而找rectangle(int,int);进行匹配,但是参数匹配不正确又会跳过,所以不会调用那个无参的构造函数,你如果只是创建对象没有参数,只要把小括号去掉就行了。

改成
void main()
{
rectangle rect1;
rectangle rect2(4,3);
}

就可以了