C++学习(4)运算符重载

2020-08-12  本文已影响0人  su945

1.运算符重载


 运算符重载的实质是函数重载
 可以重载为普通函数,也可以重载为成员函数
 把含运算符的表达式转换成对运算符函数的调用。
 把运算符的操作数转换成运算符函数的参数。
 运算符被多次重载时,根据实参的类型决定调用哪个运算符函数。
运算符重载的形式:
返回值类型 operator 运算符(形参表)
{
……
}


class Complex
{
public:
    double real, imag;
    Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) { }
    Complex operator-(const Complex & c);
};
Complex operator+(const Complex & a, const Complex & b)
{
    return Complex(a.real + b.real, a.imag + b.imag); //返回一个临时对象
}
Complex Complex::operator-(const Complex & c)
{
    return Complex(real - c.real, imag - c.imag); //返回一个临时对象
}
int main()
{
    Complex a(4, 4), b(1, 1), c;
    c = a + b; //等价于c=operator+(a,b);
    cout << c.real << "," << c.imag << endl;
    cout << (a - b).real << "," << (a - b).imag << endl;
    //a-b等价于a.operator-(b)
    return 0;
}
/*
5,5
3,3
*/

2.赋值运算符重载

有时候希望赋值运算符两边的类型可以不匹配,比如,把一个int类型变量赋值给一个Complex对象,或把一个 char * 类型的字符串赋值给一个字符串对象,此时就需要重载赋值运算符“ =”。

class String {
private:
    char * str;
public:
    String() :str(new char[1]) { str[0] = 0; }
    const char * c_str() { return str; };
    String & operator = (const char * s);
    String::~String() { delete[] str; }
};
String & String::operator = (const char * s)
{ //重载“=”以使得 obj = “hello”能够成立
    delete[] str;
    str = new char[strlen(s) + 1];
    strcpy(str, s);
    return *this;
}
int main()
{
    String s;
    s = "Good Luck,"; //等价于 s.operator=("Good Luck,");
    cout << s.c_str() << endl;
    // String s2 = "hello!"; //这条语句要是不注释掉就会出错
    s = "Shenzhou 8!"; //等价于 s.operator=("Shenzhou 8!");
    cout << s.c_str() << endl;
    return 0;
}
/*
输出:
Good Luck,
Shenzhou 8!
*/

3.运算符重载为友元函数

class Complex
{
    double real, imag;
public:
    Complex(double r, double i) :real(r), imag(i) { };
    Complex operator+(double r);
    friend Complex operator + (double r, const Complex & c);
};

4.运算符重载的注意事项

  1. C++不允许定义新的运算符 ;
  2. 重载后运算符的含义应该符合日常习惯;
     complex_a + complex_b
     word_a > word_b
     date_b = date_a + n
  3. 运算符重载不改变运算符的优先级;
  4. 以下运算符不能被重载:“ .” 、“ .*” 、“ ::” 、“ ?:” 、 sizeof;
  5. 重载运算符()、 []、 ->或者赋值运算符=时,运算符重载函数必须声明为
    类的成员函数。
上一篇 下一篇

猜你喜欢

热点阅读