简体   繁体   中英

Call non-default constructor as member initialization

I have a class "A", and a class "B" such that A contains an instance of B

class A
{
    B b = B(parameters...);
    Other thing = 3;
}

The problem with this code, is that B does not (and should not!) have a copy constructor, so the compiler is complaining

I would like to be able to call B's constructor like below, but it interprets it as a function declaration

class A
{
    B b(parameters...);
    Other thing = 3;
}

Is there a way to call the non-default constructor in the definition of the class?

Default member initializer (since C++11) only supports brace or equals initializer; you could use brace initializer here.

class A
{
    B b{parameters...};
    Other thing = 3;
};

If you need to make the copy constructor not visible you can make it private

Class B
{
     public:
     B(parameters...){};

     private:
     B(B b){};
}

As for your code i think your problem is that you need to initiate the member in the constructor of A like this:

 class A
{
    A()
      : B(parameters...)
    {
        thing = 3;
    }

    B b;
    Other thing;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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