c ++:无法从父模板类访问变量

时间:2018-06-03 23:00:02

标签: c++ oop inheritance public protected

我遇到了继承问题,特别是在处理模板类时。在以下代码中,子类似乎无法访问变量x和y:

#include <iostream>

using namespace std;

template <class Type>
class linkedListType
{
public:
    int x = 0;

    void print()
    {
        cout << "x = " << x << endl;
        cout << "y = " << y << endl;
    }

protected:
    int y = 2134;
};

template <class Type>
class unorderedLinkedList : public linkedListType<Type>
{
public:
    void print()
    {
        cout << "x = " << x << endl;
        cout << "y = " << y << endl;
    }
};

int main()
{

    linkedListType<int> a;
    unorderedLinkedList<int> b;
    a.print();
    b.print();
}

尝试编译此代码,我收到两个错误:

使用未声明的标识符'x'

使用未声明的标识符'y'

当我尝试用'常规'/非模板类编译相同的程序时(原谅我缺乏技术词汇),它编译并运行良好:

#include <iostream>

using namespace std;

class linkedListType
{
public:
    int x = 0;

    void print()
    {
        cout << "x = " << x << endl;
        cout << "y = " << y << endl;
    }

protected:
    int y = 2134;
};

class unorderedLinkedList : public linkedListType
{
public:
    void print()
    {
        cout << "x = " << x << endl;
        cout << "y = " << y << endl;
    }
};

int main()
{

    linkedListType a;
    unorderedLinkedList b;
    a.print();
    b.print();
}

它产生预期的输出:

x = 0
y = 2134
x = 0
y = 2134

当类是模板时,为什么我不能访问这些变量?任何帮助将不胜感激。

0 个答案:

没有答案