c++ - 如何避免 "' identifier' uses undefined class/struct/union 'name' "前向声明不够时的错误?

标签 c++

根据 http://msdn.microsoft.com/en-us/library/9ekhdcxs(v=vs.80).aspx ,

C2079 can also occur if you attempt to declare an object on the stack of a type whose forward declaration is only in scope.

class A;

class B {
    A a;   // C2079
};

class A {};

Possible resolution:

class A;

class C {};

class B {
   A * a;
   C c;
};
class A {};

我的问题是当我遇到以下情况时如何消除这个错误:

class A;  // Object

class B   // Container
{
   public:
     typedef int SomeTypedef;
   private:
     A a;   // C2079
};

class A {
   void Foo(B::SomeTypedef);
};

我不能在声明 B 之前声明 A,因为 A 需要使用 B 的 typedef,并且因为这个错误我不能在 A 之前声明 B。

一种可能的解决方案是使用指向 A 的指针而不是堆栈变量,但我不需要指针(在本例中)。

另一种解决方案是不使用 typedef,或者不将它放在类 B 中。但是如果它属于 B 并且我不想污染我的项目的命名空间怎么办,因为 B::SomeTypedef 比 SomeTypedef 更合适?

最佳答案

您的设计有问题,尽管嵌套类可能正是您想要的:

class B {
   public:
     typedef int SomeTypedef;
   private:
     class A {
       void Foo(SomeTypedef);
     };
     A a;
};

如果不是,这也可以用另一个在 CRTP 代码中常见的类来解决。

template<typename T>
struct foo;

class A;
class B;

template<>
struct foo<B> {
  typedef int SomeTypedef;
};

class A {
   void Foo(foo<B>::SomeTypedef);
};

class B : foo<B> {
   private:
     A a;
};

或者您可以使用另一个命名空间。

关于c++ - 如何避免 "' identifier' uses undefined class/struct/union 'name' "前向声明不够时的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10356737/

相关文章:

c++ - 编译时初始化一个非常量变量

c++ - SFML 纹理持有者已删除,但仍在范围内

c++ - 使用 C++ 通过 SOAP 连接到 TFS

c++ - 如何使用 128 个元素创建从 -3000 到 3000 的 vector

c++ - Pthread 行为 C++

c++ - header 守卫仍然会产生重新定义错误

c++ - C++ 中的策略模式与泛型

c++ - 标准中的小(不重要)缺陷?

c++ - 在未使用 constexpr 函数的返回值的情况下,g++ 编译器是否将其视为常规函数?

c++ - 为什么 std::cout 对于 [] = "12345"可以正常工作,但对于 [] = {'1' ,'2' ,'3' ,'4' ,'5' } 却不行?