C++ 运算符 -> 重载


运算符'->',被称为类成员访问运算符,可以被重载。

它被定义用于为一个类赋予"指针"行为。即可以使类对象可以通过运算符'->'访问类中的成员函数及成员变量。

运算符 '->' 重载必须是一个成员函数的形式。而且返回类型必须是指针或者是类的对象。

运算符 -> 通常与指针引用运算符 * 结合使用,用于实现"智能指针"的功能,本文没有介绍。

下面介绍一种'->'重载的实例:

#include <iostream>
#include <vector>

using namespace std;

class Dog{
public:
  static int i;
  static int j;

  void fun2()
  {
    cout << i << endl;
    cout << j << endl;
  }

};

int Dog::i = 0;
int Dog::j = 1;

class Cat
{
public:
  Dog dog1;
  Dog* operator->()
  {
    return &dog1;
  }
};

 

int main(int argc, char const *argv[])
{
  /* code */
  Dog dog;
  dog.fun2();

  Cat cat;

  //通过重载运算符'->',可以使当前类对象调用其他类中的成员,暂时不清楚更大的作用。

  cat->i = 10; 
  (cat.operator->())->j = 20;

  cat.dog1.fun2();

  return 0;
}

打印结果:

0

1

10

20

代码运行环境sublime3


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM