在类中,需要将D0
变量编写为使其成为将在基类中查找的依赖名称。m
this->m
但是在类D1
中,编译器知道在基类中查找m
而不m
被写为this->m
.
这怎么可能?为什么m
在课堂D1
上不需要写成this->m
?
#include <iostream>
#include <string>
template<class T>
class B
{
public:
B(int i) : m(i) {}
T* fb() {std::cout << "B::fb(): m = " << m << "\n"; return static_cast<T*>(this); }
protected:
int m;
};
template<class T>
class D0 : public B<T>
{
public:
D0(int i) : B<T>(i) {}
/*
* this-> makes this->m a dependent name so the lookup looks in the base class. Without this->,
* m would be an independent name and lookup would not check the base class.
*/
T* fd0() {std::cout << "D0::fd0(): m = " << this->m << "\n"; return static_cast<T*>(this); }
};
class D1 : public D0<D1>
{
public:
D1(int i) : D0<D1>(i) {}
/*
* D1 doesn't need m qualified by this-> because deriving from D0<D1> somehow
* makes it unnecessary.
*/
D1* fd1() {std::cout << "D1::fd1(): m = " << m << "\n"; return this; }
};
int main()
{
std::string s;
D1 d1(2);
d1.fd1()->fd0()->fb()->fd0()->fd1();
std::cout << "Press ENTER to exit\n";
std::getline(std::cin, s);
}