模板继承c ++ [英] template inheritance c++

查看:175
本文介绍了模板继承c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新的程序员在c ++。我第一次使用模板。



我有一个抽象类和另一个类扩展它。但是抽象类的所有受保护成员不会被其他类识别:



class0.h:

 模板< 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未在此范围内声明
}



您。有一个伟大的周=)

解决方案

发生这种情况的原因是与模板的查找规则。 >

p 不是一个依赖表达式,因为它只是一个标识符,而不是依赖于模板参数的东西。这意味着将不会搜索依赖于模板参数的基类来解析名称 p 。要解决此问题,您需要使用依赖于模板参数的内容。使用 this-> 将执行此操作。



例如

  cout<< - > p<< endl; 


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 =)

解决方案

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;

这篇关于模板继承c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆