相关疑难解决方法(0)

运算符重载的基本规则和习惯用法是什么?

注意:答案是按照特定的顺序给出的,但由于许多用户根据投票而不是给出的时间对答案进行排序,因此这里是答案索引,它们是最有意义的顺序:

(注意:这是Stack Overflow的C++常见问题解答的一个条目.如果你想批评在这种形式下提供常见问题解答的想法,那么发布所有这些的元数据的发布将是这样做的地方.这个问题在C++聊天室中受到监控,其中FAQ的想法一开始就出现了,所以你的答案很可能被那些提出想法的人阅读.)

c++ operator-overloading operators c++-faq

2074
推荐指数
8
解决办法
88万
查看次数

'std :: operator中的'operator <<'不匹配

我是一个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)

c++ c++11

16
推荐指数
3
解决办法
9万
查看次数

重载<<的返回值

#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,但上面的版本是如何表现的?

c++

3
推荐指数
1
解决办法
119
查看次数

标签 统计

c++ ×3

c++-faq ×1

c++11 ×1

operator-overloading ×1

operators ×1