0

在类中,需要将D0变量编写为使其成为将在基类中查找的依赖名称。mthis->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);
}
4

1 回答 1

0

不赘述,D1它不是类模板,它是一个具体的、非模板化的类。因此不需要使用this->来访问m.

这里有更多信息

如果您想在 中复制错误D1,以下演示了这一点:

#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) {}
    T* fd0() {std::cout << "D0::fd0(): m = " << this->m << "\n"; return static_cast<T*>(this); }
};

template <typename T>  // Now let's make this a class template
class D1 : public D0<D1<T>>
{
public:
    D1(int i) : D0<D1>(i) {}
    D1* fd1() {std::cout << "D1::fd1(): m = " << m << "\n"; return this; } // This will now produce an error
};

int main()
{
    std::string s;
    
    D1<int> d1(2);
    d1.fd1()->fd0()->fb()->fd0()->fd1();
    
    std::cout << "Press ENTER to exit\n";
    std::getline(std::cin, s);
}

错误:

error: 'm' was not declared in this scope
     D1* fd1() {std::cout << "D1::fd1(): m = " << m << "\n"; return this; }

D1现在,一旦将其作为类模板,错误就存在。

于 2020-09-25T16:36:28.110 回答