c++ - how to access member of base class with tempate inherit -
this question has answer here:
i tried c++ template class, find can't access val in class a, if don't use template, ok acccess it, can't use val in b's methold, still can use in main function, behavia strange. know why?
#include <iostream> #include <cstdio> #include "name.h" #include <map> using namespace std; template<class t> class { 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 unccomment line, program can't compiled, // cout << val << endl; cout << "in b" << endl; } }; int main() { string str = "`12"; b<string> * b = new b<string>(str); a<string> * = (a<string> *) b; b-> print(); a-> print(); cout << a-> val << endl; //but ok access val cout << b-> val << endl; return 0; }
you need reference this->val
. because val
known non-dependent type.
you can alternatively utilize using a<t>::val
before hand, or refer a<t>::val
.
the c++ faq gives (somewhat) detailed explanation of this.
Comments
Post a Comment