简体   繁体   中英

How to construct member class object from outside class (c++)

I have something that looks like this:

class Foo
{
    public:
        Foo(parameter);
}

class Bar
{
    Foo fooObject;
}

Bar::fooObject(data);

But I get:

error: expected constructor, destructor, or type conversion before '(' token

So my question is: how do I construct fooObject from outside Bar?

You can have a constructor that take an instance of Foo from outside of class and then you can copy or move that instance to your member variable. Another approach would be to take required parameters to construct an instance of Foo and then use member initializer list to construct member variable.

class Bar
{
public:
   Bar(const Foo& foo) // Copy
      : fooObject(foo)
   {
   }

   Bar(Foo&& foo) // Move
      : fooObject(std::move(foo))
   {
   }

   Bar(int example)
      : fooObject(example)
   {
   }

private:
   Foo fooObject;
}

Initialize members using a constructor and member initializer list:

class Foo{
public:
    Foo(int x);
};

class Bar{
public:
    Bar(int param);
private:
    Foo fooObject;
};

Bar::Bar(int param) : fooObject(param){};

If by outside of the class you mean the class member function definition then you would use the following syntax that goes into a source (.cpp) file:

Bar::Bar(int param) : fooObject(param){};  // ctor definition outside the class

The declarations can be placed in a header file.

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