C++ 类方法前向声明

标签 c++ cyclic-reference

有什么方法可以重新声明一个类来定义只声明到这里为止的方法吗?

例如。类似于:

class A
{
    void a();
    void b() {}
}

class A
{
    void a() {}
}

代替

class A
{
    void a();
    void b() {}
}

A::a() {}    

原因是我创建了很多代码,其中包含类定义中定义的方法,而没有使用 header 。到目前为止我还没有循环引用,但最近有需要。我不喜欢用 Type::method 语法定义一堆方法,因为在类的后面定义之前只需要知道很少的方法。

所以我有点喜欢向后声明,在循环引用之前只声明或定义几个方法,然后再定义整个类。

最佳答案

不,没有办法重新定义类。

根据 C++ 语言标准,类定义是:

class-specifier:
    class-head { member-specification_opt }

标准明确指出成员规范应该在类定义中完成:

Members of a class are data members, member functions (9.3), nested types, and enumerators. The member-specification in a class definition declares the full set of members of the class; no member can be added elsewhere.

标准还给出了重新定义类的例子:

struct S { int a; };
struct S { int a; }; // error, double definition

is ill-formed because it defines S twice.

关于C++ 类方法前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20918933/

相关文章:

java - 如何从具有循环关系的数据集中形成一棵树?

c++ - 简单的功能重载的问题

c++ - boost 缓冲区调用后丢失自定义点类型的数据

c++ - 循环引用是不好的做法吗?

python - 使用 python deepcopy 时出现 AttributeError

c# - 为什么 C# 中的类没有循环布局问题?

c++ - 如何在 C++ 中只创建一次循环 "continue"?

c++ - 创建包含另一个字符串的多个拷贝的字符串的最佳方法

c++ - 在命名空间中使用枚举