如果其他类的构造函数需要参数,如何添加类成员?
How can I add a class member if the other class' constructor requires arguments?
我用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) { ... } ;
}
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 将QIcon添加到QTableView单元格
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 当迭代器添加到添加到列表向量的结构时,迭代器停止指向值?
- Visual Studio是否不知从何而来地添加依赖项