首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于ostream&该如何解决

2012-06-13 
关于ostream&我想知道ostream&这个怎么用,所以写了个小程序测试了下,编译不了:#includeiostreamusing na

关于ostream&
我想知道ostream&这个怎么用,所以写了个小程序测试了下,编译不了:
#include<iostream>
using namespace std;
class test
{
  public:
  test();
  ostream& print(ostream& os);
  private:
  char* name;
};



test::test():name("amaking")
{}

ostream& test::print(ostream& os)
{
  os<<name<<endl;
  return os;
}

int main()
{
  test p;
  ostream os;
  p.print(os);
  system("pause");
  return 0;
}
  请教各位了!我看有些程序把ostream& os作为参数,不太明白。我把os定义成ostream&不就和cout一样了吗?

[解决办法]
cout是已经定义好的ostream对象,只需要声明即可:
extern ostream cout;

你自己定义的ostream对象要符合它的构造函数

C/C++ code
#include <iostream> using namespace std; class test { public:     test();     ostream& print(ostream& os); private:     char* name; }; test::test():name("amaking") {} ostream& test::print(ostream& os) {     os <<name <<endl;     return os; } int main() {     test p;     //ostream os;     p.print(cout);     system("pause");     return 0; }
[解决办法]
#include <iostream> 
using namespace std; 
class test 

public: 
test(); 
ostream& print(ostream& os); 
private: 
char* name; 
}; 


test::test():name("amaking") 
{} 

ostream& test::print(ostream& os) 

os <<name <<endl; 
return os; 


int main() 

test p; 

class obuf : public streambuf
{
public:
obuf():streambuf(){}
};

obuf ob;

ostream os(&ob);

p.print(os); 
system("pause"); 
return 0; 
}
[解决办法]
那我感觉去定义一个ostream& os 不是画蛇添足了啊? 

--------------------------

如果你需要输出到一个文件,怎么办? 再专门写一个函数?

热点排行