读书人

关于ostreamamp;该如何解决

发布时间: 2012-06-13 12:30:18 作者: rapoo

关于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 不是画蛇添足了啊?

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

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

读书人网 >C++

热点推荐