- C++ 基础
- C++ 首页
- C++ 概述
- C++ 环境搭建
- C++ 基本语法
- C++ 注释
- C++ Hello World
- C++ 省略命名空间
- C++ 常量/字面量
- C++ 关键字
- C++ 标识符
- C++ 数据类型
- C++ 数值数据类型
- C++ 字符数据类型
- C++ 布尔数据类型
- C++ 变量类型
- C++ 变量作用域
- C++ 多个变量
- C++ 基本输入/输出
- C++ 修饰符类型
- C++ 存储类
- C++ 运算符
- C++ 数字
- C++ 枚举
- C++ 引用
- C++ 日期和时间
- C++ 控制语句
- C++ 决策
- C++ if 语句
- C++ if else 语句
- C++ 嵌套 if 语句
- C++ switch 语句
- C++ 嵌套 switch 语句
- C++ 循环类型
- C++ while 循环
- C++ for 循环
- C++ do while 循环
- C++ foreach 循环
- C++ 嵌套循环
- C++ break 语句
- C++ continue 语句
- C++ goto 语句
- C++ 构造函数
- C++ 构造函数和析构函数
- C++ 复制构造函数
- C++ 文件处理
- C++ 文件和流
- C++ 从文件中读取
C++ 中的类成员访问运算符 (->) 重载
类成员访问运算符 (->) 可以重载,但这比较棘手。它的定义是为了赋予类类型“类似指针”的行为。-> 运算符必须是成员函数。如果使用,它的返回类型必须是指针或可以应用于其上的类的对象。
-> 运算符经常与指针解引用运算符 * 一起使用来实现“智能指针”。这些指针是行为类似于普通指针的对象,但它们会在您通过它们访问对象时执行其他任务,例如在指针被销毁时或指针用于指向另一个对象时自动删除对象。
解引用运算符 -> 可以定义为一元后缀运算符。也就是说,给定一个类 -
class Ptr {
//...
X * operator->();
};
类 **Ptr** 的对象可以用来访问类 **X** 的成员,其方式与使用指针非常相似。例如 -
void f(Ptr p ) {
p->m = 10 ; // (p.operator->())->m = 10
}
语句 p->m 被解释为 (p.operator->())->m。使用相同的概念,以下示例解释了如何重载类访问运算符 ->。
#include <iostream>
#include <vector>
using namespace std;
// Consider an actual class.
class Obj {
static int i, j;
public:
void f() const { cout << i++ << endl; }
void g() const { cout << j++ << endl; }
};
// Static member definitions:
int Obj::i = 10;
int Obj::j = 12;
// Implement a container for the above class
class ObjContainer {
vector<Obj*> a;
public:
void add(Obj* obj) {
a.push_back(obj); // call vector's standard method.
}
friend class SmartPointer;
};
// implement smart pointer to access member of Obj class.
class SmartPointer {
ObjContainer oc;
int index;
public:
SmartPointer(ObjContainer& objc) {
oc = objc;
index = 0;
}
// Return value indicates end of list:
bool operator++() { // Prefix version
if(index >= oc.a.size()) return false;
if(oc.a[++index] == 0) return false;
return true;
}
bool operator++(int) { // Postfix version
return operator++();
}
// overload operator->
Obj* operator->() const {
if(!oc.a[index]) {
cout << "Zero value";
return (Obj*)0;
}
return oc.a[index];
}
};
int main() {
const int sz = 10;
Obj o[sz];
ObjContainer oc;
for(int i = 0; i < sz; i++) {
oc.add(&o[i]);
}
SmartPointer sp(oc); // Create an iterator
do {
sp->f(); // smart pointer call
sp->g();
} while(sp++);
return 0;
}
当编译并执行上述代码时,会产生以下结果:
10 12 11 13 12 14 13 15 14 16 15 17 16 18 17 19 18 20 19 21
cpp_overloading.htm
广告