How do you use the non-default constructor for a m

2019-01-06 20:47发布

I have two classes

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

class b {
    public:
        b(); //Gives me an error here, because it tries to find constructor a::a()
        a aInstance;
}

How can I get it so that aInstance is instantiated with a(int i) instead of trying to search for a default constructor? Basically, I want to control the calling of a's constructor from within b's constructor.

4条回答
狗以群分
2楼-- · 2019-01-06 21:34

You need to call a(int) explicitly in the constructor initializer list:

b() : aInstance(3) {} 

Where 3 is the initial value you'd like to use. Though it could be any int. See comments for important notes on order and other caveats.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-06 21:37

Just use a constructor which is defined like this:

class b {
public:
    b()
    : aInstance(5)
    {}
    a aInstance;
};
查看更多
男人必须洒脱
4楼-- · 2019-01-06 21:42

Use an initialization list:

b::b() : aInstance(1) {}
查看更多
甜甜的少女心
5楼-- · 2019-01-06 21:50

I think you should use a pointer to 'a' like:

class b {
public:
    b() : aInstance(new a(5)) {}
    a *aInstance;
};

This way you will have defined behaviour. Of course you will need to free *aInstance in the destructor.

查看更多
登录 后发表回答