cpp:构造函数

#include 
#include 
using namespace std;

class rectangle
{
private:
	int *lenth = new int;
	int *wide = new int;
	int *squ = new int;
public:
	rectangle(const int l, const int w);                                          //构造函数的声明(提供初始化)(此时有参)
	rectangle();                                                                  //重载的构造函数(此时无参)
	rectangle(const rectangle &r);                                                //复制构造函数(注意这些构造函数的格式)(此时的参数必须是引用,此处用const将其作为常量来看待)
	rectangle(int _int);                                                          //类型转换构造函数
	~rectangle();                                                                 //析构函数
	rectangle & operator= (const int &r);                                         //重载运算符=,使其可以被int赋值,返回的值是rectangle的引用
	int square();
};

int main()
{
	rectangle a(5, 6);                                                            //创建一个rectangle类对象,并且以5和6初始化
	cout << "a's square is " << a.square() << endl;
	rectangle b;                                                                  //创建一个rectangle类对象,并且以无参构造函数初始化
	cout << "b's square is " << b.square() << endl;
	{
		rectangle c(a);                                                           //创建一个rectangle类对象,并且以a对c进行初始化
		cout << "c's square is " << c.square() << endl;
	}                                                                             //离开作用域,析构c
	rectangle d;
	int num = 2;
	d = num;                                                                      //此时调用类型转换构造函数,临时创建一个无名的rectangle类对象赋值给d
	cout << "d's square is " << d.square() << endl;
	return 0;
}

rectangle::rectangle(const int l, const int w)                                    //构造函数的定义(提供初始化)(此时有参)
{
	*lenth = l;
	*wide = w;
	*squ = *lenth * *wide;
}

rectangle::rectangle()
{
	*lenth = 0;
	*wide = 0;
	*squ = *lenth * *wide;
}

rectangle::rectangle(const rectangle &r)
{
	*lenth = *r.lenth;
	*wide = *r.wide;
	*squ = *lenth * *wide;
}

rectangle::rectangle(int _int)                                                    //把int型变量转换为长为int宽为1的rectangle类对象
{
	*lenth = _int;
	*wide = 1;
	*squ = *lenth * *wide;
}

rectangle::~rectangle()
{
	delete lenth;
	delete wide;
	delete squ;
	cout << "-des-" << endl;
}

int rectangle::square()
{
	return (*squ);
}

rectangle & rectangle::operator= (const int &r)
{
	*lenth = r;
	*wide = 1;
	*squ = *lenth * *wide;
	return *this;
}

你可能感兴趣的:(学习)