c++ 中的运算符重载

发布于 2024-09-26 22:35:56 字数 668 浏览 4 评论 0原文

struct T
{
        int a;
        int b;
};

class Ptr
{
public:
        Ptr(int a, int b) { t_.a = a; t_.b = b; }
        T* operator->() {return &t_;}
        T& operator*() {return t_;}

private:
        T t_;
};

int main()
{
        Ptr ptr(1, 2);
        cout << "a = " << ptr->a << " b = " << ptr->b << endl;
        cout << "a = " << ptr.operator->()->a << " b = " << ptr.operator->()->b << endl;
} 

输出:

a = 1 b = 2
a = 1 b = 2

为什么ptr->aptr.operator->()->a一样,其中的原理是什么?

struct T
{
        int a;
        int b;
};

class Ptr
{
public:
        Ptr(int a, int b) { t_.a = a; t_.b = b; }
        T* operator->() {return &t_;}
        T& operator*() {return t_;}

private:
        T t_;
};

int main()
{
        Ptr ptr(1, 2);
        cout << "a = " << ptr->a << " b = " << ptr->b << endl;
        cout << "a = " << ptr.operator->()->a << " b = " << ptr.operator->()->b << endl;
} 

Output:

a = 1 b = 2
a = 1 b = 2

Why is ptr->a the same as ptr.operator->()->a, what's the principle in it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

抹茶夏天i‖ 2024-10-03 22:35:56

因为这就是这个重载运算符的工作原理......

对于类对象 x<,表达式 x->m 被解释为 (x.operator->())->m如果 T::operator->() 存在并且该运算符被重载解析机制选择为最佳匹配函数,则为 T 类型的 /code>。

(C++§[over.ref]/1)


Because this is how this overloaded operator works...

An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism.

(C++ §[over.ref]/1)

无声静候 2024-10-03 22:35:56

这就是规则。重载运算符时->它必须返回一个指针或其他具有重载运算符 -> 的东西并且递归地应用该运算符,直到返回指针为止。最终 ->应用于该指针。这个规则是有道理的。否则你会期望运算符 ->再举一个论点。但什么类型的呢?细绳?当然不是。我的意思是,想一想,这是最(如果不是唯一)合理的方式。从这个意义上说,运算符 ->可以说是一个例外。

That's the rule. When overloading operator -> it must return either a pointer or something else that has overloaded operator -> and that operator is applied recursively until a pointer is returned. And the evenutal -> is applied to that pointer. The rule makes sense. Otherwise you'd expect that operator -> take another argument. But of what type? string? Naturally not. I mean, think about it, this is the most (if not only) reasonable way. In this sense operator -> can be said tobe an exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文