ali*_*ali 71 c++ integer class input
myclass
是我写的一个C++类,当我写的时候:
myclass x;
cout << x;
Run Code Online (Sandbox Code Playgroud)
我如何输出10
或者20.2
像一个integer
或一个float
值?
Jer*_*fin 84
通常通过operator<<
为您的班级重载:
struct myclass {
int i;
};
std::ostream &operator<<(std::ostream &os, myclass const &m) {
return os << m.i;
}
int main() {
myclass x(10);
std::cout << x;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Ric*_*ams 20
你需要重载<<
操作员,
std::ostream& operator<<(std::ostream& os, const myclass& obj)
{
os << obj.somevalue;
return os;
}
Run Code Online (Sandbox Code Playgroud)
然后当你这样做时cout << x
(在你的情况下属于哪种x
类型myclass
),它会输出你在方法中告诉它的任何内容.在上面的例子的情况下,它将是x.somevalue
成员.
如果成员的类型不能直接添加到a ostream
,那么您还需要<<
使用与上面相同的方法重载该类型的运算符.
Gui*_*cot 13
即使其他答案提供了正确的代码,也建议使用隐藏的友元函数来实现operator<<
. 隐藏友元函数的范围更有限,因此编译速度更快。由于混乱命名空间范围的重载较少,因此编译器要做的查找工作也较少。
struct myclass {
int i;
friend auto operator<<(std::ostream& os, myclass const& m) -> std::ostream& {
return os << m.i;
}
};
int main() {
auto const x = myclass{10};
std::cout << x;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这很简单,只需实施:
std::ostream & operator<<(std::ostream & os, const myclass & foo)
{
os << foo.var;
return os;
}
Run Code Online (Sandbox Code Playgroud)
你需要返回一个os的引用来链接outpout(cout << foo << 42 << endl)