Apr 29

C++重载流操作符的例子 不指定

felix021 @ 2008-4-29 16:27 [IT » 程序设计] 评论(0) , 引用(0) , 阅读(5046) | Via 本站原创 | |
Overload operator <<

felix写的一个简单例子:
#include <iostream>
using namespace std;
class testclass{
public:
  int a, b;
  testclass(int a1, int b1){
    a = a1, b = b1;
  }
  
  friend ostream & operator <<(ostream & os, testclass a1){
    cout << "a = " << a1.a << ", b = " << a1.b << endl;
    return os;
  }
  
  friend ostream & operator <<(ostream & os, testclass *a1){
    cout << "a = " << a1->a << ", b = " << a1->b << endl;
    return os;
  }
};//end of testclass

int main(){
  testclass *a1 = new testclass(1, 2);
  cout << a1;
  cout << *a1;
  getchar();
  return 0;
}

下面是更详细的重载各个流操作符的例子,原出处是Thinking In C++
copy 自 http://www.cndev.org/forum/msg.aspx?pid=233806

信息主题: 重载流操作符的例子  
信息作者: sealw
发表时间: 2005-11-08 16:43:38
阅读次数: 199
信息内容:
不好意思,来自Thinking in C++
TICPP-2nd-ed-Vol-one\TICPP-2nd-ed-Vol-one-html\Chapter12.html

//: C12:IostreamOperatorOverloading.cpp
// Example of non-member overloaded operators
#include "../require.h"
#include <iostream>
#include <sstream> // "String streams"
#include <cstring>
using namespace std;

class IntArray {
  enum { sz = 5 };
  int i[sz];
public:
  IntArray() { memset(i, 0, sz* sizeof(*i)); }
  int& operator[](int x) {
    require(x >= 0 && x < sz,
      "IntArray::operator[] out of range");
    return i[x];
  }
  friend ostream&
    operator<<(ostream& os, const IntArray& ia);
  friend istream&
    operator>>(istream& is, IntArray& ia);
};

ostream&
operator<<(ostream& os, const IntArray& ia) {
  for(int j = 0; j < ia.sz; j++) {
    os << ia.i[j];
    if(j != ia.sz -1)
      os << ", ";
  }
  os << endl;
  return os;
}

istream& operator>>(istream& is, IntArray& ia){
  for(int j = 0; j < ia.sz; j++)
    is >> ia.i[j];
  return is;
}

int main() {
  stringstream input("47 34 56 92 103");
  IntArray I;
  input >> I;
  I[4] = -1; // Use overloaded operator[]
  cout << I;
} ///:~



欢迎扫码关注:




转载请注明出自 ,如是转载文则注明原出处,谢谢:)
RSS订阅地址: https://www.felix021.com/blog/feed.php
Tags: ,
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   *非必须
网址   电邮   [注册]