简体   繁体   中英

Defining a class member that has required constructor arguments in C++

Suppose I have a class Foo whose constructor has a required argument. And further suppose that I'd like to define another class Bar which has as a member an object of type Foo :

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

class Bar {
private:
    Foo f(5);
};

Compiling this will give errors (in this exact case, g++ gives " error: expected identifier before numeric constant "). For one, Foo f(5); looks like a function definition to the compiler, but I actually want f to be an instance of Foo initialized with the value 5. I could solve the issue using pointers:

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

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

But is there a way around using pointers?

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
};

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;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM