浙大 C++ 课程学习笔记8 - 运算符重载

125 阅读1分钟

浙大 C++

网易云课堂-C++

运算符重载-基本规则

运算符重载的含义

  • Allows user-defined types to act like built in types
  • Another way to make a function call.

所谓运算符重载,可以写函数去改变运算符的行为; 当运算符对你定义的那个类进行运算时,它可以不使用默认的运算逻辑。

哪些运算符可以被重载

image.png

不能重载的运算符有:

image.png

Restrictions 约束

  • Only existing operators can be overloaded (you can't create a ** operator for exponentiation)
  • Operators must be overloaded on a class or enumeration type
  • Overloaded operators must
    • Preserve number of operands
    • Preserve precedence

运算符重载

image.png

How to overload

  • As member function
    • Implicit first argument
    • No type conversion performed on receiver
    • Must have access to class definition

Operators as member functions

class Integer
{
private:
    int v;
public:
    Integer(int n = 0) : v(n){};
    const Integer operator+(const Integer& n)const{
        return Integer(v + n.v);
    }
    void print(){cout << "value:" << v << endl;}
};

int main()
{
    Integer x(100);
    Integer y(25);
    Integer z = x+y;
    z.print();
}

member functions

image.png

image.png

x

image.png

image.png

image.png

global operators

image.png

Tip: Members vs. Free Functions

image.png

原型

Argument Passing

image.png

Return Values

image.png

The prototypes of operators

image.png

operators ++ and --

image.png

image.png

using thr overload ++ and --

image.png

Relational operators

image.png

image.png

image.png

Operator []

image.png

image.png

赋值

image.png

#include <iostream>

using namespace std;

class A
{
public:
    A() {}
};

class B
{
public:
    B(int) {}
    B(const A &) {}
};

// g++ main.cpp && ./a.out
// g++ main.cpp -o maincpp.out && ./maincpp.out
int main()
{
    B b1 = 1;
    A a;
    B b2 = a;
    b2 = a;
    return 0;
}

Automatic operator= creation

image.png

#include <iostream>

using namespace std;

class A
{

public:
    A &operator=(const A &)
    {
        cout << "inside A::operator=()" << endl;
        return *this;
    }
};

class B
{
    A a;
};

// g++ main.cpp && ./a.out
// g++ main.cpp -o maincpp.out && ./maincpp.out
int main()
{
    B m, n;
    m = n;
    return 0;
}

Assignment Operator

image.png

image.png

image.png

类型转换

Values Classes

image.png

image.png

image.png

#include <iostream>

using namespace std;

class A
{
public:
    A() {}
};

class B
{
public:
    B(const A &) {}
};

void f(B) {}

// g++ main.cpp && ./a.out
int main()
{
    A a;
    f(a); // Wants a B,Has a A
    return 0;
}

explicit

image.png

#include <iostream>

using namespace std;

class A
{
public:
    A() {}
};

class B
{
public:
    explicit B(const A &) {}
};

void f(B) {}

// g++ main.cpp && ./a.out
int main()
{
    A a;
    // f(a); // Not auto conversion allowed
    f(B(a)); // OK
    return 0;
}

Conversion operations

image.png

image.png

image.png

image.png

image.png