您的位置:首页 > 编程语言 > C语言/C++

C++重载加号运算符实现两个结构体的相加

2015-02-28 12:56 375 查看
#include<iostream>
#include<string>

using namespace std;

struct S
{
int a, b;
string str;

S operator+(const S &others)
{
S s1;
s1.a = this->a + others.a;
s1.b = this->a + others.a;
s1.str += this->str;
s1.str += others.str;
return s1;
}
};

int main()
{
S s1, s2,s3;
s1.a = 5;
s1.b = 5;
s1.str = "Hello, ";
s2.a = 6;
s2.b = 6;
s2.str = "World!";
s3 = s1 + s2;
cout << s3.a << endl;
cout << s3.b << endl;
cout << s3.str << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: