简体   繁体   中英

Error when creating an object with constructor

I ran into an error when using this code:

class Box {
public:
    Box (int);
};

Box::Box (int a) {
    //sample code   
}

int main() {
    class Anything {
        Box box (5); // error: expected identifier before numberic constant
                     // error: expected ',' or '...' before numeric constant
    };
}

The error appears on the five I filled in under class Anything. The issue disappears if I just write.

Box box (5);

Without the Anything class around it.

Any help would be appreciated.

Inside Anything ,

Box box(5);

is not valid for declaring the member variable and initializing it.

You can use:

class Anything {
    Box box;
    public:
       Anything : box(5) {}
};

or

class Anything {
    Box box = Box(5);
};

or

class Anything {
    Box box{5};
};

The reason for this is because box here:

 class Anything {
    Box box (5);
 };

Is not an object, it is a member of the class anything. You need to initialize it in the constructor ( see here ). If you want to be able to create a box you would need to do something like this:

 class Anything {
        Box box;
    public:
        Anything() : box(5) {}
 };

Then you can create an anything object as such:

Anything anything;

And it will contain a Box object box initialized with 5.

Of course all of this is pointless because you cant actually do anything with Anything . It has no other data members or functions ...

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