从模板类派生时"Class"不命名类型
"Class" does not name a type when deriving from template class
我正在努力使用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之上。
相关文章:
- '{'标记之前的预期类名,然后在预声明时无效使用不完整的类型'class class_name'
- C2011 'CMemDC':Visual Studio 2019中的'class'类型重新定义
- C++错误:"class name"之前的预期类型说明符
- "class":非法使用此类型作为表达式 如何解决?
- 如何配置 Doxygen 以在"Class Index"中包含类的类型定义?
- 无法将'Class::operator=='从"布尔"类型(类::)(类*)转换为"布尔"类型
- 获取生成错误:错误 C2011:'ProfileSettings':'class'类型重定义
- 'class MyClass' 在尝试定义静态结构实例时不会命名类型
- 'inherit class'中类型 'template class' 引用的初始化无效
- C++模板: <class> 不命名类型
- Visual Studio 2015 C2011 'Class' 类型重定义
- 错误 C2011:'SelectorBox':'class'类型重定义
- "日期":'class'类型重新定义:错误(日历.cpp文件错误)
- 从QString到Class类型
- C++ 'class'类型重新定义
- 'class'类型重定义/基类未定义
- Push_back到class类型的向量中
- C++ 代码错误(非法成员初始化、'class'类型重定义、'return':无法转换)
- 为什么C++不能用 "super class" 类型的右值初始化 "derived class" 类型的变量?
- 如何将char*转换为Class类型?