简体   繁体   English

如何在C++中的另一个类中声明一个类的构造函数

[英]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.在您的示例中, AB之间没有关系,因此您甚至没有理由尝试在另一个类中定义构造函数。 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.

相关问题 是否可以在C ++中的另一个类的构造函数中声明一个类的对象? - Is it possible to declare an object of one class in the constructor of another class in C++? 如何在C ++中声明一个对象,该对象具有另一个带有构造函数且带有参数的类的类数据 - How to declare an object in C++ that has a Class Data from another class with constructor with parameters C ++中另一个类的构造函数参数中的类参数 - Class arguments inside Constructor arguments of another Class in C++ C ++模板类,如何针对特定情况声明副本构造函数? - C++ template class, how to declare a copy constructor for a specific situation? 如何将一个C ++类声明为继承自另一个类? - How to forward declare a C++ class as inheriting from another class? C ++如何正确声明另一个类的朋友类方法 - c++ how to properly declare friend class method of another class c++ - 是否可以在引用另一个派生 class 的派生 class 中声明复制构造函数? - c++ - Is it possible to declare a copy constructor in a derived class that references another derived class? 如何在 C++ 中声明一个类 - How to declare a class in C++ 如何在C ++中的另一个类中调用一个类的构造函数? - How to call constructor of a class that is within another class in C++? 如何在一个类的构造函数中实例化到另一个类的对象? C ++ - How to instantiate an object to another class in the constructor of a class? C++
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM