我如何使用cout << myclass

myclass 是我写的C ++类,当我写的时候:


myclass x;

cout << x;

如何输出10或20.2,如integer或float值?


慕雪6442864
浏览 437回答 3
3回答

当年话下

通常通过重载operator<<您的课程:struct myclass {&nbsp;&nbsp; &nbsp; int i;};std::ostream &operator<<(std::ostream &os, myclass const &m) {&nbsp;&nbsp; &nbsp; return os << m.i;}int main() {&nbsp;&nbsp; &nbsp; myclass x(10);&nbsp; &nbsp; std::cout << x;&nbsp; &nbsp; return 0;}

蛊毒传说

您需要重载<<运算符,std::ostream& operator<<(std::ostream& os, const myclass& obj){&nbsp; &nbsp; &nbsp; os << obj.somevalue;&nbsp; &nbsp; &nbsp; return os;}然后,当您执行此操作时cout << x(在您的情况下x为type myclass),它将输出您在方法中告诉您的内容。在上面的示例中,它将是x.somevalue成员。如果不能将成员的类型直接添加到中ostream,则您需要<<使用与上述相同的方法来重载该类型的运算符。

富国沪深

这很简单,只需实现:std::ostream & operator<<(std::ostream & os, const myclass & foo){&nbsp; &nbsp;os << foo.var;&nbsp; &nbsp;return os;}您需要返回对os的引用才能链接输出(cout << foo << 42 << endl)
打开App,查看更多内容
随时随地看视频慕课网APP