有没有办法获取重载运算符>的返回值而不是其成员值?



假设我有一个带有重载运算符的类->其返回指针。然而,->需要会员,但我可以不提供会员吗?有没有办法直接得到返回值?

这里有一个代码片段来演示我的问题:我想知道是否有一种方法可以通过operator->Wrapper类获得ptr的值?

#include <iostream>
using namespace std;
struct Entry{
// could have other private fields, so `a` may not be the head of Entry.
int a;
int b;
};
class Wrapper {
public:
Wrapper(Entry* p): ptr(p) {}

Entry* operator->() {
return ptr;
}


private:
Entry* ptr;
};

int main()
{
Entry entry {12, 34};
Wrapper wrapper(&entry);
cout << wrapper->a << "n";

// is there a way to get wrapper->ptr from the operator-> directly?
}

是的。你可以简单地做,例如:

cout << wrapper.operator->();

在这种情况下,通常提供另一种方法来获得所需的指针,例如

#include <iostream>
using namespace std;
struct Entry{
// could have other private fields, so `a` may not be the head of Entry.
int a;
int b;
};
class Wrapper {
public:
Wrapper(Entry* p): ptr(p) {}

Entry* operator->() {
return ptr;
}

Entry* get() {
return ptr;
}

private:
Entry* ptr;
};

int main()
{
Entry entry {12, 34};
Wrapper wrapper(&entry);
cout << wrapper->a << "n";    
cout << wrapper.get() << "n";
}

最新更新