重载赋值运算符=
- 赋值运算符重载用于对象数据的复制
- operator= 必须重载为成员函数
- 重载函数原型为:类型 & 类名 :: operator= ( const 类名 & ) ;
#pragma warning(disable : 4996)
#include <iostream>
using namespace std;
class Name
{
public:
Name(const char* c)
{
len = strlen(c);
this->m_name = new char[len + 1];
strcpy(this->m_name, c);
cout << "构造函数" << endl;
}
//返回值当左值需要返回一个引用
Name &operator=(const Name &n)
{
//先释放旧的内存
if (this->m_name != NULL)
{
delete[] m_name;
len = 0;
}
//根据新的对象分配新的内存大小
len = n.len;
this->m_name = new char[len+1];
//把新的值赋值给当前变量
strcpy(this->m_name, n.m_name);
return *this;
}
void GetName()
{
cout << "Name = " << m_name << endl;
}
~Name()
{
cout << "析构函数" << endl;
}
private:
char *m_name;
int len;
};
void PlayObj()
{
Name n1("ZhangSan");
n1.GetName();
Name n2("WangWu");
n2.GetName();
Name n3 = "LiSi";
n3.GetName();
n3 = n2 = n1;
n3.GetName();
}
int main()
{
PlayObj();
system("pause");
return 0;
}
重载=操作符的步骤:
1、释放当前旧的内存
2、根据新的对象分配新的内存大小
3、把新的值赋值给当前变量
重载赋值运算符[]
- 运算符 [] 和 () 是二元运算符
- [] 和 () 只能用成员函数重载,不能用友元函数重载
[] 运算符用于访问数据对象的元素,重载格式 类型 类 :: operator[] ( 类型 ) ;
class Vector
{
public:
Vector(int n)
{
size = n;
v = new int[size];
}
int & operator[](int n)
{
return v[n];
}
~Vector()
{
delete[] v;
size = 0;
}
private:
int *v;
int size;
};
void PlayObj()
{
Vector v(5);
for (int i = 0; i < 5; i++)
{
v[i] = i + 1;
}
cout << "v[3] = " << v[3] << endl;
}
int main()
{
PlayObj();
system("pause");
return 0;
}
v[i] = i + 1;
看上面的语句,v[i]作左值,因此需要返回一个引用。
重载函数调用符 ()
- 运算符 [] 和 () 是二元运算符
- [] 和 () 只能用成员函数重载,不能用友元函数重载
() 运算符用于函数调用,重载格式 类型 类 :: operator() ( 表达式表 ) ;
class Complex
{
public:
double FunAddr(double x, double y)
{
return x * x + y * y;
}
double operator()(double x, double y)
{
return x * x + y * y;
}
};
void PlayObj()
{
Complex c;
cout << "Addr = " << c.FunAddr(2.5, 3.5) << endl;
cout << "Addr = " << c(2.5, 3.5) << endl;
}
int main()
{
PlayObj();
system("pause");
return 0;
}
为什么不要重载&&和||操作符
1、&&和||是C++中非常特殊的操作符
2、&&和||内置实现了短路规则
3、操作符重载是靠函数重载来完成的
4、操作数作为函数参数传递
5、C++的函数参数都会被求值,无法实现短路规则