运算符重载入门demo

#include "pch.h"
#include <iostream>
using namespace std;

class A
{
public:
    A(int x, int y)
    {
        this->x = x;
        this->y = y;
    }
    void printA()
    {
        cout << x << " + " << y << "i" << endl;
    }

    int x;
    int y;
};

A myadd(A a, A b)
{
    A temp(a.x + b.x, a.y + b.y);

    return temp;
}
//运算符重载
A operator+(A a, A b)
{
    A temp(a.x + b.x, a.y + b.y);

    return temp;
}

int main()
{
    //int a = 1, b = 2;
    //int c = a + b;

    A a(1, 1), b(2, 2);
    A c1 = myadd(a, b);
    c1.printA();

    A c2 = a + b;
    c2.printA();
    cout << "Hello World!\n"; 
}

猜你喜欢

转载自www.cnblogs.com/jly594761082/p/10569433.html