gpt4 book ai didi

c++ - 运算符重载在 Visual Studio 2013 中编译但不是 gcc

转载 作者:行者123 更新时间:2023-11-28 02:57:03 24 4
gpt4 key购买 nike

我有一个类,我要像这样重载 << 和 + 运算符:

    friend MyObject operator+(MyObject lhs, MyObject rhs){
MyObject obj;
obj.Property = lhs.Property + rhs.Property;
return obj;
}

friend std::ostream& operator<<(std::ostream& os, MyObject& n) {
os << MyObject.Property; //property is a double
return os;
}

这在 Visual Studio 和 gnu++98 中编译都没有问题。我也可以毫无问题地这样称呼他们:

MyObject obj1, obj2;
obj1.PutInValidState();
cout << obj1;
obj1 = obj1 + obj2;

但是,当我像这样同时调用它们时:

cout << obj1 + obj2;

Visual Studio 将编译它(并给出正确的输出),但 gnu++98 给我错误“'中的 'operator<<' 不匹配” std::operator<<(std::basic_ostream&, const char*)"。我可以通过将 const 添加到函数定义中的参数来使其在两者中编译,如下所示:

friend std::ostream& operator<<(std::ostream& os, const MyObject& n) {

这是怎么回事?为什么我需要 const 才能使其在 gnu++98 中工作但在 Visual Studio 中不能工作?

最佳答案

cout << obj1 + obj2;

的语法糖
operator<<(cout, operator+(obj1,obj2));

在这里您可以看到 operator<<() 重载中的 n 参数被绑定(bind)到 operator+() 返回的值,这是一个临时对象。现在,在 C++ 中,有一个规则,即非常量引用参数不能绑定(bind)到临时对象,这就是它不能在 gcc 中编译的原因。

另一方面,Visual Studio 有一个语言扩展,它允许非常量引用参数绑定(bind)到临时对象。我希望它没有,因为该扩展是将代码移植到其他编译器时困扰我的扩展之一。

关于c++ - 运算符重载在 Visual Studio 2013 中编译但不是 gcc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21745085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com