I tried c++ template class, but I find that I can't access val in class A, if I don't use template, it is ok to acccess it, even I can't use val in B's methold, I still can use it in main function, this behavia is really strange. does anybody know why?
#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;
}