如何使用的cout << MyClass的

问题描述:

myclass是一个C++类是我写的,当我写:如何使用的cout << MyClass的

myclass x; 
cout << x; 

如何输出1020.2,像integerfloat价值?

这很容易,只需要实现:

std::ostream & operator<<(std::ostream & os, const myclass & foo) 
{ 
    os << foo.var; 
    return os; 
} 

你需要为了返回到操作系统的引用链outpout(COUT < <富< < ENDL)

+19

这是一个无限递归函数。它得到了赞扬!你一定要喜欢这个周末! – 2010-06-05 19:56:41

通常由超载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; 
} 
+0

这将输出构造函数值'10'? – 2016-06-27 14:15:32

+1

请注意,如果'myclass'有任何'private'字段,并且您希望'operator 2017-01-28 18:28:51

+0

不应该是'const myclass&m'而不是'myclass const&m'? – Nubcake 2017-08-15 21:06:59

你需要重载<<操作,

std::ostream& operator<<(std::ostream& os, const myclass& obj) 
{ 
     os << obj.somevalue; 
     return os; 
} 

然后当你做cout << x(其中xmyclass类型的你的情况),这将输出无论你的方法告诉它。在上面的例子中,它将是x.somevalue成员。

如果成员的类型不能直接添加到ostream,那么您也需要使用与上述相同的方法为该类型重载<<运算符。

+4

这是左移运算符,而不是“流运算符”。在Iostreams的上下文中,它是插入或提取操作符,但它绝不是流操作符。 – 2010-06-05 20:04:41

+1

对不起,是的,你是对的。这正是我在我的脑海中所称的,因为我倾向于只在处理流时才使用它。在这种情况下,它将是您所说的插入操作符,而不仅仅是流操作符。我已经更新了我的答案以消除这一点。 – 2010-06-05 20:11:27