(zz)对cout << 重载的源代码

本文展示了一个使用 C++ 编写的简单类 CA 的实例,该类包括构造函数、拷贝构造函数、赋值运算符重载及多种操作符重载方法。此外,还提供了一个自定义流操作符和自定义流操纵符的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
 
 return 0;
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值