放牧代码和思想
专注自然语言处理、机器学习算法
    This thing called love. Know I would've. Thrown it all away. Wouldn't hesitate.

如何重载cout<<

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;

class CA
{
public:
CA(int i) : m_i(i)
{
cout << "CA@" << this << " Constructor(" << i << ")" << endl;
}

CA(const CA& a) : m_i(a.m_i)
{
cout << "CA@" << this << " CopyConstructor(" << &a << ")" << endl;
}

CA& operator = (const CA& a)
{
m_i = a.m_i;
cout << "CA@" << this << " Operator=(" << &a << ")" << endl;
}

~CA()
{
cout << "CA@" << this << " Destructor()" << endl;
}

int GetValue() const
{
return m_i;
}

bool operator()()
{
return (m_i == 0) ? false : true;
}

string operator() (const CA& a)
{
return (m_i == 0) ? "false" : "true";
}

operator string ()
{
return (m_i == 0) ? "convert to false" : "convert to true";
}
       
protected:
CA()
{
cout << "CA@" << this << " Constructor()" << endl;
}

protected:
int m_i;
};

ostream& operator << (ostream &o, const CA& a)
{
return (o << "CA@" << &a << " Val=" << a.GetValue());
}

ostream& MyManipulator(ostream& o)
{
return (o << "|myend|");
}

class CMyManipulator
{
public:
CMyManipulator():m_i(0)
{
  
}

CMyManipulator(int i):m_i(i)
{
  
}

~CMyManipulator()
{
  
}

int GetValue() const
{
   return m_i;
}

protected:
int m_i;
};

ostream& operator <<(ostream &o, const CMyManipulator& m)
{
for (int i=0; i<m.GetValue(); ++i)
{
   o << "|myend" << i << "|";
}

return o;
}

int main()
{
CA a(0);
cout << a << endl;
cout << a() << endl;
cout << a(a) << endl;
cout << string(a) << endl;

cout << "some string" << MyManipulator << endl;
cout << "some string" << CMyManipulator(3) << endl;
system("pause");
return 0;
}

知识共享许可协议 知识共享署名-非商业性使用-相同方式共享码农场 » 如何重载cout<<

评论 欢迎留言

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

我的作品

HanLP自然语言处理包《自然语言处理入门》