开发者

Using 'new' keyword with struct in c++

开发者 https://www.devze.com 2023-04-12 20:11 出处:网络
#include \"PQueue.h\" struct arcT; struct coordT { double x, y; }; struct nodeT { string na开发者_StackOverflow社区me;
#include "PQueue.h"

struct arcT;

struct coordT {
    double x, y;
};

struct nodeT {
    string na开发者_StackOverflow社区me;
    coordT* coordinates;
    PQueue<arcT *> outgoing_arcs;
};

struct arcT {
    nodeT* start, end;
    int weight;
};

int main(){
    nodeT* node = new nodeT; //gives error, there is no constructor
}

My purpose is to create a new nodeT in heap. Error is:

error C2512: 'nodeT' : no appropriate default constructor available


PQueue<arcT *> does not have an appropriate default constructor, so a default constructor for nodeT cannot be generated by the compiler. Either make an appropriate default constructor for PQueue<arcT *> or add a user-defined default constructor for nodeT which constructs outgoing_arcs appropriately.


If the currently posted code in the question is an exact copy, then the only possible cause for this error is that PQueue<…> doesn’t define a default constructor, and defines another constructor instead.

Otherwise this code would compile.

More precisely, since you didn’t define a constructor for your structures, C++ tries to auto-generate them. It can only do this, though, as long as all its member variables are appropriately default constructible or initialisable. std::string has a default constructor, and coordT*, being a pointer, can be initialised. So only PQueue<…> remains as the culprit.


THis may not be your problem but you've only declared one pointer on this line in arcT :-

nodeT* start, end;

You've declared start as a pointer and end as an actual nodeT object. Is this what you wanted to do?

0

精彩评论

暂无评论...
验证码 换一张
取 消