本章是介绍重载操作符 -> 的研究,上代码先
#include "stdafx.h"
#include <iostream>
#include <string>
template<typename T>
class A1 {
public:
A1(T* t) : m_imp(t) {
std::cout << "A1()" << std::endl;
}
~A1() {
std::cout << __FUNCTION__ << std::endl;
}
T* operator ->() {
std::cout << __FUNCTION__ << std::endl;
return m_imp;
}
private:
T* m_imp;
};
template<typename T>
class A2 {
public:
A2(T* t) : m_imp(t) {}
A1<T> operator ->() {
std::cout << __FUNCTION__ << std::endl;
A1<T> a(m_imp);
return a;
}
private:
T* m_imp;
};
template<typename T>
class A3 {
public:
A3(T* t) : m_imp(t) {}
A2<T> operator ->() {
std::cout << __FUNCTION__ << std::endl;
A2<T> a(m_imp);
return a;
}
private:
T* m_imp;
};
class Test {
public:
void show() {
std::cout << m_a << std::endl;
}
private:
int m_a;
};
template<typename T>
class B1 {
public:
B1(T* t) : m_imp(t) {
std::cout << __FUNCTION__ << std::endl;
}
B1(T& t) : m_imp(&t) {
std::cout << __FUNCTION__ << std::endl;
}
T* operator->() {
std::cout << __FUNCTION__ << std::endl;
return m_imp;
}
private:
T* m_imp;
};
int _tmain(int argc, _TCHAR* argv[])
{
Test* pt = new Test();
A1<Test> a1(pt);
a1->show();
a1.A1::operator ->()->show();
A2<Test> a2(pt);
a2->show();
// 可自动推导出如下式
// a2.A2::operator ->().A1::operator ->()->show();
A3<Test> a3(pt);
a3->show();
// 可自动推导出如下式
// a3.A3<Test>::operator ->().A2::operator ->().A1::operator ->()->show();
B1<Test> b1(pt);
b1->show();
B1<B1<Test> > b2(b1);
b2->operator ->()->show();
b2.B1<B1<Test> >::operator ->()->B1<Test>::operator ->()->show();
// b2->show(); 错误,不能递归推导
return 0;
}
基于以上代码,可以看出 对->运算符的重载,编译器无法进行递归推导.
这种递归推导,编译器可以在编译期处理,为什么编译器不处理这种递归推导,留待思考
以上代码在vc编译器测试通过。