C++ Class is not base of itself

2019-04-26 16:29发布

问题:

Im not exactly sure how much information is needed to answer this, so tell me if more information is needed.

Im modifying a large code i wrote when i suddenly encountered this message: error: type 'integer' is not a direct base of 'integer'. i know its an inheritance problem, but im not inheriting other classes.

The code that is causing this problem is

integer(const std::string & val, uint16_t base): integer(val.begin(), val.end(), base) {}

and

integer(iterator start, iterator end, uint16_t base) 

has been defined.

What do I need to do to fix this?

EDIT: im compiling with -std=c++0x, which according to the answers, i should be able to compile, unless my compiler is old: gcc 4.6.2 i think

回答1:

It looks like you're trying to call another constructor directly. You can't do that in C++03, but you can do exactly that in C++11:

class SomeType  {
    int number;

public:
    SomeType(int new_number) : number(new_number) {}
    SomeType() : SomeType(42) {}
};

You'll need g++ 4.7 or newer for this to work, 4.6 doesn't support this feature yet, even with -std=c++0x, which I tested with both versions on my system.



回答2:

It is not allowed to invoke other constructors of the same class like that (there are delegating constructors in C++11). You need to initialise the members of the class (as you have probably done in the other constructor).

EDIT:

According to C++0x/C++11 Support in GCC , delegating constructors were implemented in GCC v4.7



回答3:

You can't call a constructor of the same class in the initializer list of a different constructor (in C++03). But you can initialize the members accordingly:

integer(const std::string & val, uint16_t base): _start(val.begin())
                                                 _end(val.end())
                                                 _base(base)
{}


回答4:

It's not supported in g++-4.6 ("Delegating constructors | N1986 | No"), but is supported in 4.7.