理解运算符重载 3

#include "stdafx.h"
#include <iostream>
#include <string>
//
//函数重载
//

namespace operator_test
{
//
//先定义一个类
//
class CObject
{
friend std::ostream& operator<<(std::ostream& out, CObject& object);
public:
CObject(int a) : m_a(a)
{

}

int Get()
{
return m_a;
}

CObject& operator+(CObject& obj2)
{
this->m_a += obj2.Get();
return *this;
}
private:
int m_a;
};


std::ostream& operator<<(std::ostream& out, CObject& object)
{
out << object.m_a;
return out;
}
}

void test_operator_test()
{
operator_test::CObject obj1(10);
operator_test::CObject obj2(20);

//
//返回值,把int operator+(CObject& obj2)改成 CObject& operator+(CObject& obj2)
//

std::cout << obj1 + obj2 << std::endl;

//std::cout << obj1 + obj2返回一个std::ostream&,接着往这个返回的ostream写入std::endl; 
}

posted @ 2013-11-24 12:55  sysnap  阅读(149)  评论(0编辑  收藏  举报