[英]Defining a class member that has required constructor arguments in C++
假设我有一个类Foo
其构造函数有一个必需的参数。 并且进一步假设我想定义另一个类Bar
,它具有Foo
类型的对象作为成员:
class Foo {
private:
int x;
public:
Foo(int x) : x(x) {};
};
class Bar {
private:
Foo f(5);
};
编译它会产生错误(在这种情况下,g ++给出“ error: expected identifier before numeric constant
”)。 一个, Foo f(5);
看起来像编译器的函数定义,但我实际上希望f
是一个用值5初始化的Foo
实例。我可以使用指针解决问题:
class Foo {
private:
int x;
public:
Foo(int x) : x(x) {};
};
class Bar {
private:
Foo* f;
public:
Bar() { f = new Foo(5); }
};
但有没有办法使用指针?
你的指针版本非常接近 - 修改如下(见下面的评论):
class Foo {
private:
int x;
public:
Foo(int x) : x(x) {};
};
class Bar {
private:
Foo f; // Make f a value, not a pointer
public:
Bar() : f(5) {} // Initialize f in the initializer list
};
如果你有C ++ 11支持,可以在声明点初始化f
,但不能用圆括号()
初始化:
class Bar {
private:
Foo f{5}; // note the curly braces
};
否则,您需要使用Bar
的构造函数初始化列表。
class Bar {
public:
Bar() : f(5) {}
private:
Foo f;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.