注意:答案是按照特定的顺序给出的,但由于许多用户根据投票而不是给出的时间对答案进行排序,因此这里是答案的索引,它们是最有意义的顺序:
(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)
我是一个C++新手.我在这里尝试了我的第一个程序.我的眼睛这个程序是正确的.
#include <iostream>
using namespace std;
class mystruct
{
private:
int m_a;
float m_b;
public:
mystruct(int x, float y)
{
m_a = x;
m_b = y;
}
};
int main()
{
mystruct m = mystruct(5,3.14);
cout << "my structure " << m << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是我得到了很多错误.不知道为什么?
cout.cpp: In function ‘int main()’:
cout.cpp:26:29: error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = std::char_traits<char>]((* & std::cout), ((const char*)"my structure ")) << m’
cout.cpp:26:29: note: candidates are:
/usr/include/c++/4.6/ostream:110:7: note: std::basic_ostream<_CharT, …Run Code Online (Sandbox Code Playgroud) #include <iostream>
using namespace std;
struct info {
info(int x, int y) : x(x), y(y) {}
int x;
int y;
};
ostream& operator<<(ostream& out, const info &myinfo){
out << myinfo.x << " " << myinfo.y;
return cout;
}
int main() {
info a(1,2);
info b(3,4);
cout << a << " " << b << endl;
}
Run Code Online (Sandbox Code Playgroud)
即使有不正确的过载,上述程序的输出似乎也很好operator <<.
谁能告诉我这个重载问题的影响是什么?我知道重载函数应该返回out而不是cout,但上面的版本是如何表现的?