[英]How to declare a constructor of a class inside another class in C++
For example:例如:
class A
{
public:
A();
int a;
};
class B
{
A::A()
{
a = 1;
}
};
The best way to answer this is in a single word: Don't.回答这个问题的最好方法是一个词:不要。 In your example, there is no relationship between
A
and B
, so there is no reason for you to even try to define the constructor in another class.在您的示例中,
A
和B
之间没有关系,因此您甚至没有理由尝试在另一个类中定义构造函数。 The only reason that you would want to mention the constructor of A
in B
is if B
is derived from A
.您想在
B
提及A
的构造函数的唯一原因是B
是否从A
派生。 You want to keep parts of A
with A
, not separate them into other classes and make it a nightmare for readability and maintenance.您希望将
A
保留在A
,而不是将它们分成其他类,并使其成为可读性和维护的噩梦。 The short version is that you should keep all parts of A
with A
, so don't try to put them somewhere else.简短的版本是你应该用
A
保留A
所有部分,所以不要试图把它们放在其他地方。
No, you can't.不,你不能。
Quoted from the standard [class.mfct] paragraph 1 (emphasized mine):引自标准[class.mfct] 第 1 段(强调我的):
A member function may be defined in its class definition, in which case it is an inline member function, or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.
一个成员函数可以在它的类定义中定义,在这种情况下它是一个内联成员函数,或者如果它已经被声明但没有在它的类定义中定义,它可以在它的类定义之外定义。 A member function definition that appears outside of the class definition shall appear in a namespace scope enclosing the class definition.
出现在类定义之外的成员函数定义应出现在包围类定义的命名空间范围内。
In your example, the definition appear in a class scope, which contradicts to this rule.在您的示例中,定义出现在类范围内,这与此规则相矛盾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.