有什么方法可以重新声明一个类来定义只声明到这里为止的方法吗?
例如。类似于:
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/