gpt4 book ai didi

c++ - C++中的运算符重载

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:48 25 4
gpt4 key购买 nike

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是一样的,它的原理是什么?

最佳答案

因为这就是这个重载运算符的工作方式...

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)

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

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