【问题标题】:how to access member of base class with tempate inherit [duplicate]如何使用模板继承访问基类的成员[重复]
【发布时间】:2013-05-04 17:24:35
【问题描述】:

我试过c++模板类,但是发现我在A类中无法访问val,如果我不使用模板,访问它是可以的,即使我在B的方法中不能使用val,我仍然可以在主函数中使用它,这种行为真的很奇怪。 有人知道为什么吗?

#include <iostream>
#include <cstdio>
#include "name.h"
#include <map>
using namespace std;

template<class T>
class A {
    public:
        T val;
        A(T obj) {
            val = obj;
        }
        virtual void print() {
            cout << "in A" << endl;
        }
};

template<class T>
class B: public A<T> {
    public:
        B(T obj):A<T>(obj) {
        }
        void print() {
//if you unccomment this line, this program can't be compiled,
//            cout << val << endl;
            cout << "in B" << endl;
        }
};

int main() {
    string str = "`12";
    B<string> * b = new B<string>(str);
    A<string> * a = (A<string> *) b;
    b-> print();
    a-> print();
    cout << a-> val << endl;
//but it is ok to access val like this
    cout << b-> val << endl;
    return 0;
}

【问题讨论】:

    标签: c++


    【解决方案1】:

    您需要将其引用为this-&gt;val。这是因为val 是所谓的非依赖类型

    您也可以事先使用using A&lt;T&gt;::val,或使用A&lt;T&gt;::val 引用它。

    C++ FAQ 对此给出了(有些)详细的解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 2016-02-21
      相关资源
      最近更新 更多