繁体   English   中英

模板继承c ++

[英]template inheritance c++

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

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

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
}

谢谢。 有一个伟大的一周=)

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

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

例如

cout << this->p << endl;

要在依赖基类中查找名称,需要满足两个条件

  • 这是必要的查找是不是不合格
  • 名称必须依赖

C ++ 03中所述的这些规则与未经修改的C ++ 98规定的规则不同,后者满足第二个项目符号(使名称相关) 足以查找在从属基类中声明的名称。

在实例化时查找依赖名称,并且除非非限定查找之外的查找不会忽略依赖基类。 需要满足这两个条件才能找到在依赖基类中声明的名称, 单独使用它们都不够 要满足这两个条件,您可以使用各种结构

this->p
class1::p

两个名称p都是相关的,第一个版本使用类成员访问查找 ,第二个版本使用限定名称查找

我在VC9中没有得到编译器错误。 但是,代码有几个问题:首先,它不需要是一个模板类,因为它是当前编写的...但是你可能只是为这个问题简化了它? 其次,基类应该有一个虚拟析构函数。

#include <iostream>

using namespace std;

class class0 {
public:
   virtual ~class0(){}

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

class class1 : public class0 {
public:
    void printChar();
};

void class1::printChar(){
    cout << p << endl;//p was not declared in this scope
}

int main() {
   class1 c;
   c.printChar();
   return 1;
}

由于您正在学习模板,我建议您在学习时不要混合概念(继承和模板)。 从这样一个简单的例子开始......

#include <iostream>
#include <string>

using namespace std;

template <typename T>
T add(const T& a, const T& b) {
   return a + b;
}

int main() {
   int x = 5;
   int y = 5;

   int z = add(x, y);
   cout << z << endl;

   string s1("Hello, ");
   string s2("World!");

   string s3 = add(s1, s2);
   cout << s3 << endl;

   return 1;
}

上面代码中的重要概念是我们编写了一个知道如何添加整数和字符串(以及其他许多类型)的函数。

很抱歉恢复这么老的问题,但我只是想添加一些我觉得有价值的东西,如果你的成员函数中有很多很多“p”。

class class1:public class0<T> {
public:
    using class0<T>::p; // add this line and in all member functions 
                        // will assume that "p" is the p from class0<T>
                        // very useful if you have hundreds of "p":s
                        // and don't want to replace every single one with "this->p"
    void printChar();
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM