# include<iostream>
using namespace std;
class rectangel
{
public:
rectangel(){cout<<"构造一个长方形a!\n";}
rectangel(int l,int w){length=l;width=w;cout<<"长方形的面积为:"<<length*width<<endl;}
//在构造函数中,我们把l的值付给length,把w的值付给width。rectangel b(3,4)通过l和w把值付给了length和width。
rectangel(int l,int w,int h){length=l;width=w;height=h;cout<<"长方形的体积为:"<<length*width*height<<endl;}
private:
int length;
int width;
int height;
};
int main()
{
rectangel a;
rectangel b(3,4);
rectangel c(3,4,5);
return 0;
}
运行结果:
# include<iostream>
using namespace std;
class rectangel
{
public:
rectangel():length(3),width(5){cout<<"长方形a的面积为:"<<length*width<<endl;}
/*在构造函数的后面有一个冒号,然后是成员变量的名称和一对小括号,若有多个成员变量进行初始化,
要用都好隔开;最后大括号中是函数的功能部分。*/
private:
int length;
int width;
int height;
};
int main()
{
rectangel a;
//因为构造函数不带参数,我们也只能使用不带参数的构造的对象。
//rectangel(3,5);这样写是错误的
return 0;
}
运行结果:
# include<iostream>
using namespace std;
class rectangel
{
public:
rectangel():length(3),width(5){cout<<"长方形a的面积为:"<<length*width<<endl;}
//rectangel(int l,int w){length=l;width=w;cout<<"长方形a的面积为:"<<length*width<<endl;}
//若使用注释掉的语句,就会不通过,其实下面的语句是对成员变量的赋值;而上面的语句才是对成员变量的初始化。
private:
const int length;
//加上一个const
int width;
};
int main()
{
rectangel a;
//rectangel(3,5);
return 0;
}
由于常量和引用只能被初始化,不能被赋值。
因此最好在构造函数的函数头中对常量和引用进行初始化。