#include "stdafx.h"
#include <string>
#include <iostream>
namespace friend_test
{
class CObject
{
friend std::ostream& operator<<(std::ostream& os, CObject& object);
public:
CObject(std::string name, int age) : m_age(age), m_name(name)
{
}
std::string& getname()
{
return m_name;
}
int getage()
{
return m_age;
}
private:
int m_age;
std::string m_name;
};
//
//非类成员函数.
//
//std::ostream& operator<<(std::ostream& out, CObject& object)
//{
// out << "name is : " << object.getname() << std::endl << "age is : " << object.getage() << std::endl;
// return out;
//}
std::ostream& operator<<(std::ostream& out, CObject& object)
{
out << "name is : " << object.m_name << std::endl << "age is : " << object.m_age << std::endl;
return out;
}
}
void test_friend_test()
{
friend_test::CObject obj1("sysnap", 28);
std::cout << "name is : " << obj1.getname() << std::endl; //CObject是用于存储年纪和名字
std::cout << "age is : " << obj1.getage() << std::endl;
/*
output:
name is : sysnap
age is : 28
*/
//这样输出比较繁琐,有时候我就想std::cout << obj1 << std::endl;就能实现跟上面俩条语句一样的功能,怎么办
//很明显需要重载 << 运算符
std::cout << obj1 ; //把obj1和std::cout压入堆栈,然后调用std::ostream& operator<<(std::ostream& out, CObject& object)
//在控制台输出是在std::ostream& operator<<(std::ostream& out, CObject& object)里面调用cout实现的.
//而且当数据多的时候,为获取每个类的私有成员写一个getxxx函数,有点繁琐,最好还需要
//能直接访问类的私有成员,所以可以考虑用友元函数.
std::cout << obj1 ;
}