53 lines
703 B
C++
53 lines
703 B
C++
|
// 重载 * 和 ->
|
||
|
// 注意: * 和 -> 的重载不能有参数
|
||
|
#include <iostream>
|
||
|
#include <cstring>
|
||
|
#include <cstdlib>
|
||
|
|
||
|
using namespace std;
|
||
|
|
||
|
class A
|
||
|
{
|
||
|
private:
|
||
|
int x;
|
||
|
|
||
|
public:
|
||
|
explicit A(int x) : x(x) {}
|
||
|
void printA()
|
||
|
{
|
||
|
cout << "x = " << x << endl;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
class B
|
||
|
{
|
||
|
private:
|
||
|
A *mA;
|
||
|
|
||
|
public:
|
||
|
B(int x) : mA(new A(x))
|
||
|
{
|
||
|
}
|
||
|
|
||
|
A *operator->()
|
||
|
{
|
||
|
return mA;
|
||
|
}
|
||
|
A &operator*()
|
||
|
{
|
||
|
return *mA;
|
||
|
}
|
||
|
};
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
B b(20);
|
||
|
// b -> 执行 B 类的 -> 重载,返回 A 类的对象的指针
|
||
|
b->printA();
|
||
|
|
||
|
B b2(30);
|
||
|
// *b 执行 B 类的 * 重载函数,返回 A 类的对象
|
||
|
(*b2).printA();
|
||
|
return 0;
|
||
|
}
|