如果其他类的构造函数需要参数,如何添加类成员?

How can I add a class member if the other class' constructor requires arguments?

本文关键字:添加 何添加 成员 其他 构造函数 参数 如果      更新时间:2023-10-16

我用C++编码不多,所以如果这是微不足道的,请原谅我。

我的类"Foo"看起来有点像这样:

class Foo {
    public: Foo(int n) { }
};
另一个类"

Bar"现在应该有一个类型为"Foo"的类成员。

class Bar {
    private: Foo f;
};

这显然失败了,因为"Foo"没有不需要任何参数的构造函数。然而,像Foo f(1);这样的东西也会失败。

有没有办法解决这个问题?还是我应该在这里使用指针?

class Bar {
public:
    Bar():f(0) { }
    explicit Bar(int n):f(n) { }
    private: Foo f;
};

编写自己的c-tors,使用initializer-list,或在Foo中编写不带参数的c-tor,或使用pointer,或者用C++11可以编写

class Bar {
public:
    private: Foo f = Foo(1);
};

这可以通过两种不同的方式处理。

(1) 为class Foo提供适当的参数构造函数

您可以引入无参数构造函数Foo()或编辑接受默认参数的当前构造函数,即 Foo(int n = 0)

(2)在Bar内调用class Foo的构造函数,并具有适当的节格

例如

class Bar {
...
  Bar() : f(0) {}  // (a) pass the argument explicitly 
  Bar(int n) : f(n) {} // (b) receive argument inside Bar()
};

你可能有一个Foo的默认构造函数,或者在类Bar中使用Foo的指针,稍后再设置一个对象。

我想如果你的Foo需要一个参数来构造,有两种可能性:
- 要么你的酒吧将使用一个静态数字来构建他自己的Foo(所有酒吧在Foo中都有相同的n)
- 您的酒吧在其会员Foo中将有不同的号码。然后,您可以将一个数字传递给 Bar 构造函数,如下所示:

class Bar {
    Bar(int n) : Foo(n) { ... } ;
    }