c++ - 间接运算符如何通过运算符重载返回指针地址

标签 c++

我想理解下面的代码:

class EdgeIterator {

  EdgeIterator() {}

  EdgeIterator(const EdgeList edges) {}

  EdgeIterator begin() { return *this; }


  EdgeIterator& operator*() { return *this; }

}

begin 函数中 return *this 返回和 EdgeIterator 并且,在 operator* 函数中,它如何返回 EdgeIterator&

最佳答案

begin() 按值返回,因此它返回 *this 的拷贝。

operator*() 通过引用返回,因此它返回对 *this 的引用。

为了更好的解释,下面是类似的代码:

struct X
{
  std::string a;
  X copy() { return *this; }
  X& ref() { return *this; }
};

int main()
{
  X x{"Hi"};
  x.copy().a = "Bye";
  std::cout << x.a << '\n'; // prints Hi
  x.ref().a = "Bye";
  std::cout << x.a << '\n'; // prints Bye
}

[Live example]

关于c++ - 间接运算符如何通过运算符重载返回指针地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56595583/

相关文章:

java - 在 CORBA 客户端/服务器应用程序中将 unsigned long(从 C++)分配给 long(Java)?

c++ - 并发读写的嵌入式数据库

c++ - 如何修复 "clang: error: linker command failed with exit code 1 (use -v to see invocation)"错误?

c++ - 小型记录器类

c++ - 如何获取 GL 库/头文件?

c++ - 使用CppUTest问题 “expected type-specifier before ‘(’ token 进行Yaml-cpp配置解析器测试”

C++ 是否 reinterpret_cast 总是返回结果?

c++ - 从 .o 目标文件中提取函数的原始机器代码?

c++ - C 与 C++ 中的指针

C++ const char* 指针赋值