我试过c++模板类,但是发现我在A类中无法访问val,如果我不使用模板,可以访问它,即使我在B的方法中无法使用val,我仍然可以使用它在 main 函数中,这种行为真的很奇怪。有人知道为什么吗?
#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;
}