c++ - 如何在 C++ 中重载 '->' 运算符?

标签 c++ operator-overloading

我想围绕另一个类编写一个简单的包装器。一个小例子:

class MyClass {
   ...
   int someMember();
   ...
};

class MyClassRefernence{
   ...
   MyClass* ptr;
   MyClass& operator *();
   ...
};

如果我现在有如下代码:

MyClassReference ref;
... // Init the ref and the pointer ptr.
int a = (*ref).someMember(); // this works but is nasty
int b = ref->someMember(); // Compile error

所以我的问题是:有没有一种方法可以使用更漂亮的 -> 运算符来代替 (*...). 构造?

最佳答案

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

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

相关文章:

c++ - 为什么 cin.getline 会分配给字符数组,但使用 '=' 却不会?

c++ - 在运算符重载中使用 "const"作为参数

c++ - 模板运算符的不明确重载

c++ - C++14 中 decltype(auto) 的转换函数

c++ - g++ 和 clang++ 对流输入和无符号整数的不同行为

c - 使用预处理器的 C 中的运算符重载语法

使用模板的 C++ 重载输出运算符

c++ - 重载 << 并出现重复符号链接(symbolic link)错误

c++ - GCC 4.7.2 中损坏的 std::unique_ptr

C++11 move 构造函数和赋值运算符