Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

template inheritance c++

i am a new programmer in c++. and i am using templates for the first time.

i have an abstract class and another class extending it. but all the protected members of the abstract class are not recognised by the other class:

class0.h:

template<class T>
class class0 {

protected:
    char p;
public:
    char getChar();
};

**class1.h**
template<class T>
class class1:public class0<T> {
public:
    void printChar();
};
template<class T>
void class1<T>::printChar(){
    cout<< p<<endl;//p was not declared in this scope
}

thank you. have a great week =)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason that this is happening is to do with the lookup rules for templates.

p isn't a dependent expression because it is just an identifier and not something that depends on the template parameter. This means that base classes that are dependent on the template parameter won't be searched to resolve the name p. To work around this issue you need to use something that does depend on the template parameter. Using this-> will do this.

e.g.

cout << this->p << endl;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...