简体   繁体   中英

C++ - Initializing class member with an instance

my question is as follows: Suppose I have:

class Foo
{
public:
    Foo() {}
    void setInt(int i) { myInt = i; }
    int getInt() { return myInt; }
private:
    int myInt;
};

class Bar
{
public:
    Bar(Foo f) { /* do something with f.getInt() */ }
};

Now I have another class that has Bar as a member vairable:

class BarUser
{
public:
    BarUser();
private:
    Bar bar;
};

I want to write BarUser's constructor, however I want to initialize Bar with a Foo member that has 3 as its integer. Ie:

Foo f;
f.setInt(3);
Bar b(f);

However since I have Bar as a class member, I cannot write all this code in the initialization list... What I mean is:

BarUser::BarUser() : bar(/* Foo after executing f.setInt(3) */)
{ ... }

Suppose assignment operator is not allowed for Bar - how can I initialize it as intended?

Thanks!

If you can't change Foo , write a function:

Foo make_foo(int i) { 
     Foo f; 
     f.setInt(i); 
     return f;
}

then initialize with bar(make_foo(3)) .

You've sort of shot yourself in the foot by giving Foo a constructor but no int constructor. You might be better off adding an explicit constructor to Foo that takes an int .

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