Overload Operators
程序员文章站
2022-07-14 22:29:48
...
内容:
说明:
操作重载
示例代码:
// 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;
}
知识点:
操作符:<< 和 + 的重载
上一篇: Mybatis基础(part 1)
下一篇: Day 2: Operators
推荐阅读
-
方法重载(overload)与方法重写(override)
-
Java overload和override的区别分析
-
There are no operators in the program to be executed 可能的原因
-
PHP和JAVA中的重载(overload)和覆盖(override) 介绍
-
重写(OverRide)/重载(Overload)
-
解决Backup Operators用户权限设置问题的方法
-
PHP面向对象程序设计模拟一般面向对象语言中的方法重载(overload)示例
-
Groovy - Groovy ambiguous method overload
-
SQL Mathematical Operators and String Operators
-
282. Expression Add Operators