欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Overload Operators

程序员文章站 2022-07-14 22:29:48
...

内容:

Overload Operators

说明:

操作重载

示例代码:

// Overload_Operators.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Complex
{
public:
    int a, b;
    void input( string s )
    {
        int v1 = 0;
        int i = 0;

        while( s[i] != '+' )
        {
            v1 = v1 * 10 + s[i] - '0';
            i++;
        }

        while( s[i] == ' ' || s[i] == '+' || s[i] == 'i' )
        {
            i++;
        }

        int v2 = 0;

        while( i < s.length() )
        {
            v2 = v2 * 10 + s[i] - '0';
            i++;
        }

        a = v1;
        b = v2;
    }
};

ostream& operator<<( ostream& os, const Complex& c )
{
    return os << c.a << ( c.b > 0 ? '+' : '-' ) << 'i' << c.b;
}

Complex operator+( const Complex& a, const Complex& b )
{
    return { a.a + b.a, a.b + b.b };
}

int main()
{
    Complex x, y;
    string s1, s2;
    cin >> s1;
    cin >> s2;
    x.input( s1 );
    y.input( s2 );
    Complex z = x + y;
    cout << z << endl;
    system( "pause" );
    return 0;
}


知识点:

操作符:<< 和 + 的重载