关于ostream&该如何解决
关于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对象要符合它的构造函数
我想知道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 不是画蛇添足了啊?
--------------------------
如果你需要输出到一个文件,怎么办? 再专门写一个函数?