标签:
cout << "hello" << endl << "world";
输出:
hello world
int x;
cout << "input the num what you want:";
cin >> x;
cout << "the num you input is:";
cout << x;
struct Complex
{
int a;
int b;
};
// 操作符的重载
Complex operator+ (Complex &c1, Complex &c2)
{
Complex k;
k.a = c1.a + c2.a;
k.b = c1.b + c2.b;
return k;
}
int main()
{
Complex a1 = { 1, 2 };
Complex a2 = { 3, 4 };
Complex a3 = operator+(a1, a2);
// 也可以直接:
Complex a3 = a1 + a2;cout << "a3.a=" << a3.a << endl;
cout << "a3.b=" << a3.b << endl;
while (1);
}
class Complex
{
int a; // 默认的是私有的
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
~Complex()
{
}
// 指定朋友,友元函数
friend Complex operator+ (Complex &c1, Complex &c2);
};
// 操作符的重载
Complex operator+ (Complex &c1, Complex &c2)
{
Complex k;
// 这样可以通过对象访问到private成员
//k.a = c1.getA() + c2.getA();
//k.b = c1.getB() + c2.getB();
k.a = c1.a + c2.a; // 通过对象直接访问
k.b = c1.b + c2.b;
return k;
}
int main()
{
Complex a1(1, 2);
Complex a2(3, 4);
Complex a3 = a1 + a2;
cout << "a3.a = " << a3.getA() << endl;
cout << "a3.b = " << a3.getB() << endl;
while (1);
}
ostream& operator<< (ostream& out, Complex &c)
{ // 这个地方看不懂
out << c.a << " and " << c.b << endl;
return out;
}
int main()
{
Complex a1(1, 2);
Complex a2(3, 4);
Complex a3 = a1 + a2;
cout << a3 << endl;
while (1);
}
class Complex
{
int a; // 默认的是私有的
int b;
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
int getA()
{
return a;
}
int getB()
{
return b;
}
~Complex()
{
}
// 这里第一个对象有传入 this 指针,所以只需要一个就可以了,
Complex operator+ (Complex &c2);
};
Complex Complex :: operator + (Complex &c2)
{
Complex k;
k.a = this->a + c2.a;
k.b = this->b + c2.b;
return k;
}
int main()
{
Complex a1(1, 2);
Complex a2(3, 4);
Complex a3 = a1 + a2;
cout << a3.getA() << endl;
cout << a3.getB() << endl;
while (1);
}
标签:
原文地址:http://www.cnblogs.com/qxj511/p/4917694.html