成员函数形式的运算符声明和实现与成员函数类似,首先应当在类定义中声明该运算符,声明的具体形式为:
返回类型 operator 运算符(参数列表);
#include <iostream>
using namespace std;
class point
{
private:
int ix;
int iy;
public:
//构造函数只能显示调用,不能=
explicit point(int ix1,int iy1)
:ix(ix1)
,iy(iy1)
{
cout<<"构造函数初始化:"<<endl;
}
//赋值构造函数
point & operator=(const point &rhs)
{
ix=rhs.ix;
iy=rhs.iy;
cout<<"重载=运算符:"<<endl;
}
//复制构造函数
point (const point &rhs)
:ix(rhs.ix)
,iy(rhs.iy)
{
cout<<"拷贝构造函数:"<<endl;
}
void print()
{
cout<<"("<<ix<<","<<iy<<")"<<endl;
}
};
|
int main()
{
point p1(1,2);
p1.print();
point p2=p1;
//复制构造函数(隐式),p2之前没有创建
p2.print();
point p3(p1);
p3.print();
point p4(3,4);
p4.print();
p1=p4; //赋值操作,p1之前已经创建
p1.print();
}
|
///
/// @file computer3.cpp
/// @author meihao1203(meihao19931203@outlook.com)
/// @date 2017-12-17 14:15:36
///
#include<iostream>
#include<string.h>
using namespace std;
class computer
{
char *_brand;
float _price;
public:
computer(const char* brand,float price)
:_price(price)
{
_brand = new char[strlen(brand)+1];
strcpy(_brand,brand);
}
~computer()
{
delete []_brand;
_brand = NULL;
cout<<"~computer()"<<endl;
}
computer(const computer &rhs)
:_price(rhs._price)
{
_brand = new char[strlen(rhs._brand)+1];
strcpy(_brand,rhs._brand);
cout<<"computer(const computer &)"<<endl;
}
#if 0
computer & operator=(const computer &rhs) //简单的修改指针,会导致内存泄露;析构函数多次释放段错误
{
this->_brand = rhs._brand;
this->_price = rhs._price;
cout<<"computer & operator = (const computer &)"<<endl;
}
#endif
|
computer & operator = (const computer &rhs)
{
delete []_brand;
_brand = NULL;
_brand = new char[strlen(rhs._brand)+1];
strcpy(_brand,rhs._brand);
_price = rhs._price;
return *this; //返回本身
}
void print()
{
cout<<"品牌:"<<_brand<<endl;
cout<<"价格:"<<_price<<endl;
}
};
int main()
{
computer cr1("IBM",1234.56);
cr1.print();
computer cr2("ASUS",7890.12);
cr2.print();
cr1 = cr2; //computer.operator=(cr2)
cr1.print();
return 0;
}
|