简体   繁体   English

如何声明自定义类型的成员对象,然后在C ++中初始化?

[英]How do I declare a member object of custom type and initialize afterwards in C++?

The following code works when run at cpp.sh : cpp.sh上运行时,以下代码有效:

#include <iostream>

class B{
    public:
        B(int i);
        int i;
};

B::B(int i) {
    this->i = i;
}

class A{
    public:
        A(B *b);
        B *b;
};

A::A(B *b) {
    this->b = b;
}


int main()
{
  B b(8);
  A a(&b);
  std::cout << a.b->i;
}

It creates an object of type B and stores a pointer in an object of type A . 它创建类型B的对象,并将指针存储在类型A的对象中。 What I want to do is to only pass the integer (8 in this case) and create and store the full object in a without creating an intermediate object. 我想要做的是只通过整数(8在这种情况下),并创建和保存完整的对象在a没有创建中间对象。

But when I try to declare a object of type B (not just a pointer) inside A, I get a no matching function for call to 'B::B() error. 但是,当我尝试在A内声明B类型的对象(而不仅仅是指针)时,我得到了一个no matching function for call to 'B::B()错误。

This is the approach I tried, which doesn't work: 这是我尝试过的方法,不起作用:

#include <iostream>
// B i not changed
class B{
    public:
        B(int i);
        int i;
};

B::B(int i) {
    this->i = i;
}

class A{
    public:
        A(int i);
        B b;
};

A::A(int i) {
    this->b(i); //initialize
}


int main()
{
  A a(8);
  std::cout << a.b->i;
}

Why do I get a "no matching function" error when declaring a B b; 为什么在声明B b;时出现“无匹配函数”错误B b; variable instead of a pointer B *b; 变量而不是指针B *b; ? Is my approach this->b(i); 我的方法是- this->b(i);this->b(i); to initialize a member after declaration correct? 在声明正确后初始化成员?

Your class B does not provide a constructor taking no arguments (the implicitly defined default constructor gets deleted once you declare any other constructor). 您的类B没有提供不带任何参数的构造函数(声明了任何其他构造函数后,隐式定义的默认构造函数将被删除)。 When you define another class A with a data member of type class B , the system cannot initialize this data member unless you explicitly define which constructor of B with which arguments should be used. 当您使用类型class B的数据成员定义另一个类A时,系统无法初始化该数据成员,除非您明确定义应该使用哪个B构造函数以及哪些参数。

You can overcome this by... 您可以通过...克服

  1. Call the constructor of b in an member-initializer list of A 's constructor, ie A::A(int i) : b(i) {} A的构造函数的成员初始化器列表中调用b的构造函数,即A::A(int i) : b(i) {}

  2. Default-Initialize data member b when defining it, ie in A , write B b = B(1) ; 定义数据成员b时默认初始化它,即在A ,写B b = B(1)

  3. Define a (user-defined) default constructor in B , eg B() : i(0) {} B定义一个(用户定义的)默认构造函数,例如B() : i(0) {}

  4. Define a default value in the (sole) constructor of B , eg B(int i=0) B的(唯一的)构造函数中定义一个默认值,例如B(int i=0)

I'd prefer option 1; 我更喜欢选项1; Options 2..4 are listed just for completeness. 列出选项2..4仅出于完整性考虑。

Note that any code, regardless which, in the body of a constructor is not considered as "data member initialization". 请注意,构造函数主体中的任何代码(无论哪个代码)均不视为“数据成员初始化”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM