1

假设我有一个类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成为一个Foo初始化为 5 的实例。我可以使用指针来解决这个问题:

class Foo {
private:
   int x;
public:
    Foo(int x) : x(x) {};
};

class Bar {
private:
    Foo* f;
public:
    Bar() { f = new Foo(5); }
};

但是有没有办法使用指针?

4

2 回答 2

3

Your version with pointers is very close - modify it as follows (see comments below):

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
};
于 2013-08-13T20:29:38.000 回答
1

If you have C++11 support, can initialize f at the point of declaration, but not with round parentheses ():

class Bar {
private:
    Foo f{5}; // note the curly braces
};

Otherwise, you need to use Bar's constructor initialization list.

class Bar {
public:
    Bar() : f(5) {}
private:
    Foo f;
};
于 2013-08-13T20:29:28.033 回答