gpt4 book ai didi

c++ - 无法在 C++ 中重载 Dot '.' 运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:01:18 24 4
gpt4 key购买 nike

我很难理解 Stroustrup 的解释,如果对“.”进行运算符重载,那么必须面临哪些困难?被允许。

请参阅 Bjarne Stroustrup 的这句话:

Operator . (dot) could in principle be overloaded using the same technique as used for ->. However, doing so can lead to questions about whether an operation is meant for the object overloading . or an object referred to by . For example:

class Y {
public:
void f();
// ...
};

class X { // assume that you can overload .
Y* p;
Y& operator.() { return *p; }
void f();
// ...
};

void g(X& x)
{
x.f(); // X::f or Y::f or error?
}

在上面的例子中,为什么在执行 x.f() 时会有任何混淆?

Y& operator.() { return *p; }

这是我的想法:

  1. operator.() 是在 x 上调用的,因此应该调用 Y& operator.()( return *p; } 不是很明显和直观吗?
  2. 返回指向类型 Y 对象的 *p 后,最终应调用 Y::f()(而不是 X::f( ) )

我在 Stroustup 的解释中遗漏了什么?为什么不直接?

最佳答案

有一些进展:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4477.pdf .由于一些技术问题,这不会出现在 C++17 中,但我希望在 C++20 中看到它。

关于c++ - 无法在 C++ 中重载 Dot '.' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42183631/

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