简体   繁体   中英

“Expected a type specifier” error when creating an object of a class inside another class declaration

I have a class called scratch and have used scratch.h to declare it.

Now I have another class called scratch2 under scratch2.h and want to create an object of scratch as a shared pointer .

This is the syntax I used inside scratch2 class declartion:

std::shared_ptr<scratch> newObject(new scratch());

But I am getting this error: Error: Expected type specifier

So I tried this instead:

std::shared_ptr<scratch> newObject2 = std::make_shared<scratch>();

which works fine. Can anyone please tell me why the first one isn't working?

My scratch.h code:

#ifndef _SCRATCH_
#define _SCRATCH_

#include <iostream>

class scratch {
private:
    int _a;
    float _b;
    std::string _s;
public:
    scratch();
    scratch(int a, float b, std::string n);
    ~scratch();
};
#endif

and my scratch2.h:

#ifndef _SCRATCH_2_
#define _SCRATCH_2_

#include "scratch.h"
#include <memory>

class scratch2 {
    std::shared_ptr<scratch> newObject(new scratch()); // Expected a type specifier error occurs here
    std::shared_ptr<scratch> newObject2 = std::make_shared<scratch>(); // works fine here
};

#endif

Because in the context of declaring class members:

std::shared_ptr<scratch> newObject(new scratch());

This initially looks to the compiler as a class method declaration. C++'s syntax is very complicated. You can look at the entire declaration and understand what it's trying to do, but the compiler is parsing keywords one keyword at a time, and sees this:

type name ( ...

inside a class declaration, and this starts to look like a class method declaration, and that's what the compiler tried to parse, and failed.

The formal specification of the C++ language spills a lot of ink on the subject of how things should be declared, mindful of the current state of compiler technology.

You need to work with the compiler, and use an alternate syntax that's unambiguous:

std::shared_ptr<scratch> newObject = std::shared_ptr<scratch>(new scratch());

Verified with gcc 5.3

Inside of a class definition, there are only two ways you're allowed to initialize your members. You can use = and you can use {} . You are not allowed to use () :

struct foo {
    int x = 4;  // OK
    int y{7};   // OK
    int z(12);  // error
};

Admittedly, the compiler error in this case is extremely unhelpful.

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