gpt4 book ai didi

c++ - 涉及临时对象的运算符重载决策顺序

转载 作者:可可西里 更新时间:2023-11-01 15:07:10 25 4
gpt4 key购买 nike

考虑以下最小示例:

#include <iostream>

using namespace std;

class myostream : public ostream {
public:
myostream(ostream const &other) :
ostream(other.rdbuf())
{ }
};

int main() {
cout << "hello world" << endl;

myostream s(cout);
s << "hello world" << endl;

myostream(cout) << "hello world" << endl;
}

在 g++ 和 Visual C++ 上的输出都是

hello world
hello world
0x4012a4

写入临时对象的版本,myostream(cout) , 似乎更喜欢成员运算符 ostream::operator<<(void *) , 而不是免费运营商 operator<<(ostream &, char *) .对象是否有名称似乎有所不同。

为什么会这样?我该如何防止这种行为?

编辑:现在从各种答案中可以清楚地看出为什么会发生这种情况。至于如何防止这种情况,以下似乎很有吸引力:

class myostream : public ostream {
public:
// ...
myostream &operator<<(char const *str) {
std::operator<<(*this, str);
return *this;
}
};

然而,这会导致各种歧义。

最佳答案

如果一个对象没有名字(即它是一个临时对象),它不能绑定(bind)到一个非常量引用。具体来说,不能绑定(bind)到第一个参数:

operator<<(ostream &, char *)

关于c++ - 涉及临时对象的运算符重载决策顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2245780/

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