从模板类派生时"Class"不命名类型

"Class" does not name a type when deriving from template class

本文关键字:Class 类型 派生      更新时间:2023-10-16

我正在努力使用c++模板。这是我的代码的简化版本。实际上,我把它分成了。cpp和。h两个文件,但是为了显示问题,我把它写得很短。

#include <iostream>
template<typename T>
class GenericColor
{
};
template<typename T>
class RGB : public GenericColor<T>
{
public:
    HSV toHSV();
};
class HSV : public GenericColor<double>
{
};

编译结果为:

prog.cpp:12:2: error: ‘HSV’ does not name a type
  HSV toHSV();
  ^
https://ideone.com/HnvC6F

编译器从上到下读取。你需要转发声明HSV。

说:

class HSV;

class RGB

当编译器读取RGB的定义时,HSV还没有宣称。你需要事先申报。以下代码是正确的:

template<typename T>
class GenericColor
{
};

class HSV : public GenericColor<double>
{
};
template<typename T>
class RGB : public GenericColor<T>
{
public:
    HSV toHSV();
};

中定义类并不容易秩序。在这种情况下,您只需声明您需要的,并定义它以后。这被称为前向声明。请看下面的代码:

#include <iostream>
template<typename T>
class GenericColor
{
};
class HSV; // the forward-declaration
template<typename T>
class RGB : public GenericColor<T>
{
public:
    HSV toHSV();
};
// the definition of HSV
class HSV : public GenericColor<double>
{
};

需要先定义HSV,然后才能从成员函数返回它。在本例中,只需剪切粘贴HSV类def在RGB类def之上。