gcc中的C++错误和成功VS.

1 c++ linux gcc visual-c++

下面的代码不能在gcc 4.7中编译,但在VS(9,10,11)中编译也遵循gcc输出.

#include <iostream>

using namespace std;

class A
{
public:
    virtual void M() = 0;
};

class B
{
public:
    inline B& operator<<(A &value)
    {
        value.M();
        return *this;
    }
};

class C: public A
{
public:
    virtual void M()
    {
        cout << "Hello World" << endl; 
    }
};

int main()
{
    B b;
    C c;

    b << c;   //line not erro
    b << C(); //Line with error

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

gcc日志

$ g ++ main.cpp -o test main.cpp:在函数'int main()'中:
main.cpp:36:12:错误:'b << C()'
main中'operator <<'不匹配. cpp:36:12:注意:候选人是:main.cpp:14:15:注意:B&
B :: operator <<(A&)main.cpp:14:15:注意:没有
来自'C的参数1的已知转换'到'A&'

jua*_*nza 7

C++不允许您将非const引用绑定到临时,就像您尝试在此处执行的操作一样:

b << C();
//   ^^^^ temporary
Run Code Online (Sandbox Code Playgroud)

VS允许您将其作为"扩展"执行此操作,但它是非标准的,因此不可移植,正如您所发现的那样.

您需要的是const相关运营商的参考:

inline B& operator<<(const A& value)
//                   ^^^^^
Run Code Online (Sandbox Code Playgroud)