[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
class three_d {
int x, y, z; //三个坐标值
public:
three_d(int a, int b, int c) { x = a; y = b; z = c; }
three_d operator+(three_d op2); //重载'+'运算符
friend ostream &operator<<(ostream &stream, three_d &obj);
operator int() {return x * y * z; } //创建的转换函数
};
//输出3个坐标值 -- 通过类 three_d 的插入符
ostream &operator<<(ostream &stream, three_d &obj)
{
stream << obj.x << ", ";
stream << obj.y << ", ";
stream << obj.z << "\n";
return stream; //返回流对象
}
three_d three_d::operator+(three_d op2)
{
three_d temp(0, 0, 0);
temp.x = x + op2.x;
temp.y = y + op2.y;
temp.z = z + op2.z;
return temp;
}
int main()
{
three_d a(1, 2, 3), b(4, 5, 6);
cout << a << b;
cout << b + 100; //这里对象b被转换为int类型整数
cout << "\n";
a = a + b; //两个three_d类型对象相加,没有发生呢类型转换
cout << a;
return 0;
}