当前位置:优学网  >  在线题库

在c++中从模板类继承成员变量:使用未声明的标识符;你是说'nlcatd::数据'?

发表时间:2022-07-22 00:05:33 阅读:65

我是C++新手,我试着写一个简单的继承模板类的片段,我写了这个简单的代码,它给了我这样的错误.


#include <iostream>
using namespace std;

template <class T>
class Base
{
public:
    T m_data;
};

template <class T>
class child_template: public Base<T>
{
public:
    void print_child()
    {
        cout << m_data << endl; // error: use of undeclared identifier 'm_data'; did you mean 'child_class::m_data'?
        // cout << this->m_data << endl; // no error
    }
};

int main()
{
    child_template<int> child_obj;
    child_obj.m_data = 20;
    child_obj.print_child();
    return 0;
}

错误如下:

template_cls_inherit.cpp:17:17: error: use of undeclared identifier 'm_data'; did you mean '__nl_cat_d::__data'?
        cout << m_data << endl; // error: use of undeclared identifier 'm_data'; did you mean 'child_class::m_data'?
                ^~~~~~
                __nl_cat_d::__data
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/nl_types.h:90:8: note: '__nl_cat_d::__data' declared here
        void    *__data;
                 ^
template_cls_inherit.cpp:17:17: error: '__nl_cat_d::__data' is not a member of class 'child_template<int>'
        cout << m_data << endl; // error: use of undeclared identifier 'm_data'; did you mean 'child_class::m_data'?
                ^~~~~~
template_cls_inherit.cpp:26:15: note: in instantiation of member function 'child_template<int>::print_child' requested here
    child_obj.print_child();
              ^
2 errors generated.

虽然我使用了this-&gtm_data而不是m_data并且错误消失了,但我仍然不明白为什么我应该使用this指针?

🎖️ 优质答案
相关问题