标签:
一般运算符重载
在进行对象之间的运算时,程序会调用与运算符相对应的函数进行处理,所以运算符重载有两种方式:成员函数和友元函数。成员函数的形式比较简单,就是在类里面定义了一个与操作符相关的函数。友元函数因为没有this指针,所以形参会多一个。
// 运算符重载,这里又叫赋值函数
string& operator =(const string &other);
// 运算符重载,但这里要用友元函数才行
friend ostream& operator << (ostream &os,const string &str);
string &string::operator=(const string &other)
{
if(this == &other)
return *this;
delete []m_data;
m_data = NULL;
m_data = new char[strlen(other.m_data)+1];
strcpy(m_data,other.m_data);
return *this;
}
ostream& operator << (ostream &os,const string& str) // 返回引用用于实现链式表达式
{
os<<str.m_data;
return os;
}
成员函数重载与友元函数重载的区别:
If you define your operator overloaded function as member function, then compiler translates expressions like s1 + s2
into s1.operator+(s2)
. That means, the operator overloaded member function gets invoked on the first operand. That is how member functions work!
But what if the first operand is not a class? There‘s a major problem if we want to overload an operator where the first operand is not a class type, rather say double
. So you cannot write like this 10.0 + s2
. However, you can write operator overloaded member function for expressions like s1 + 10.0
.
To solve this ordering problem, we define operator overloaded function as friend
IF it needs to access private
members. Make it friend
ONLY when it needs to access private members. Otherwise simply make it non-friend non-member function to improve encapsulation!
两种重载方式的比较:
注意事项:
标签:
原文地址:http://www.cnblogs.com/balingybj/p/4772843.html