C++重载运算符

时间:2022-05-10 17:34:37

本文主要讲述加号运算符“+”,自增运算符“++”,流提取运算符运“>>”,流插入运算符"<<"的重载。

先给出Vector类:

class Vector
{
    public:
        Vector(double a = 0, double b = 0) {x = a, y = b;}  //构造函数
        Vector(const Vector& v){x = v.x, y = v.y;}  //拷贝构造函数
        Vector operator + (const Vector& v);  //重载+
        Vector operator ++ ();  //重载前置自增运算符“++”
        Vector operator ++ (int);  //重载后置自增运算符“++”
        friend istream& operator >> (istream& input, Vector& v);  //重载“>>”
        friend ostream& operator << (ostream& output, Vector& v);  //重载“<<”

    private:
        double x;
        double y;
};

1.重载加号

代码实现

Vector Vector::operator + (const Vector& v)
{
    return Vector(x + v.x, y + v.y);  //此处调用拷贝构造函数
};

“/”、“*”、“-”的重载类似。


2.重载自增运算符

自增运算符分为前置和后置两种。对于前置自增,重载函数返回自增后的对象,对于后置自增,重载函数返回自增前的对象。为了区分,C++规定,在对自增运算符进行重载时,若额外加上一个int型形参,就表明重载的是后置自增。

(1)前置自增

Vector Vector::operator ++ ()
{
    ++x;
    ++y;
    return *this;
};

(2)后置自增

Vector Vector::operator ++ (int)
{
    Vector temp(*this);
    x++;
    y++;
    return temp;
};

“--”的重载类似。


3.“>>”和“<<”

前面的运算符均重载为类的成员函数,但是对于流插入和流提取运算符却不能如此,而是重载为类的友元函数。

“>>”重载

istream& operator >> (istream& input, Vector& v)
{
    cout << "x: ";
    input >> v.x;
    cout << "y: ";
    input >> v.y;
    return input;
};

“<<”重载

ostream& operator << (ostream& output, Vector& v)
{
    output << "Vector:" << "(" << v.x << "," << v.y << ")";
    return output;
};

以下是完整的程序:

#include <iostream>
using namespace std;

class Vector
{
    public:
        Vector(double a = 0, double b = 0) {x = a, y = b;}
        Vector(const Vector& v){x = v.x, y = v.y;}
        Vector operator + (const Vector& v);
        Vector operator ++ ();
        Vector operator ++ (int);
        friend istream& operator >> (istream& input, Vector& v);
        friend ostream& operator << (ostream& output, Vector& v);

    private:
        double x;
        double y;
};

Vector Vector::operator + (const Vector& v)
{
    return Vector(x + v.x, y + v.y);  //此处调用拷贝构造函数
};

Vector Vector::operator ++ ()
{
    ++x;
    ++y;
    return *this;
};

Vector Vector::operator ++ (int)
{
    Vector temp(*this);
    x++;
    y++;
    return temp;
};

istream& operator >> (istream& input, Vector& v)
{
    cout << "x: ";
    input >> v.x;
    cout << "y: ";
    input >> v.y;
    return input;
};

ostream& operator << (ostream& output, Vector& v)
{
    output << "Vector:" << "(" << v.x << "," << v.y << ")";
    return output;
};

int main()
{
    Vector v1, v2;
    cin >> v1 >> v2;
    v1++;
    ++v2;
    cout << v1 << endl << v2 << endl;
    return 0;
}

运行:

C++重载运算符

C++重载运算符