【问题标题】:Using an enum from a Forward Declared Class使用前向声明类中的枚举
【发布时间】:2020-01-28 14:10:29
【问题描述】:

当前问题:

我需要从一个前向声明的类中访问一个枚举,类似于这种情况:

Human.h

#include "Dog.h"
class Human{
public:
  enum Language: uint32_t {
    None = 0,
    English = 1,
    Japanese= 2,
  };
}

Dog.h

class Human;

class Dog{
   void understand(Human::Language speech);
}

Dog.cxx

#include "Dog.h"
#include "Human.h"

void Dog::understand(Human::Language speech) {  
   // Do stuff with Human::Language
   return;
}

错误:

  • IDE 告诉我 Dog.cxx 的实现与 Dog.h 的减速不兼容,在错误提示中引用枚举为 <erro-type>(只有红色波浪线)
  • 编译时,任何提及 Dog.h/c.xx 中的枚举都会引发错误,无法找到枚举

额外信息:

  • MSVC 15 2017
  • 程序的完整架构要​​求枚举可以像这样访问
  • 前向减速是强制性的,以解决我的程序中未在此处看到的循环依赖

【问题讨论】:

  • (1) 你的意思是在 Dog 类中是 Human::Language 而不是 Dog::Language? (2) 重复 - stackoverflow.com/questions/13842006/…?
  • Dog::Language 的定义在哪里?我只能看到Human::Language的定义
  • 我的错误很抱歉,它已被修复
  • 为什么需要前向声明?你不能只包括标题吗?也许我们需要更多的上下文。
  • 一般来说,你不能对前向声明的类做任何事情,除非声明一个指向它的指针。

标签: c++ enums


【解决方案1】:

基本上答案是否定的,您不能在这种情况下转发声明枚举。您的选择是:

  1. 将枚举移动到轻量级基类中。
struct HumanBase
{
  enum Language: uint32_t {
    None = 0,
    English = 1,
    Japanese= 2,
  };
};

//fwd declare
struct Human;
  1. 将枚举移出类。
enum HumanLanguage : uint32_t {
  None = 0,
  English = 1,
  Japanese= 2,
};
struct Human;

如果你以后需要,你可以这样做:

struct Human
{
  typedef HumanLanguage Language;
};
  1. 将所有使用枚举的方法更改为模板(在某些情况下可能有效,在其他情况下可能无效)
class Dog{
   template<typename LanguageType)
   void understand(LanguageType speech);
};

【讨论】:

  • 我发现选项 1 是最简单和最有效的
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2011-11-20
  • 2010-09-09
  • 2013-02-14
相关资源
最近更新 更多