使用“新” c++ 中带有结构的关键字

发布于 2024-12-10 00:40:21 字数 450 浏览 1 评论 0原文

#include "PQueue.h"

struct arcT;

struct coordT {
    double x, y;
};

struct nodeT {
    string name;
    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
}

我的目的是在堆中创建一个新的nodeT。错误是:

错误 C2512:“nodeT”:没有合适的默认构造函数可用

#include "PQueue.h"

struct arcT;

struct coordT {
    double x, y;
};

struct nodeT {
    string name;
    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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

作妖 2024-12-17 00:40:21

PQueue 没有合适的默认构造函数,因此编译器无法生成 nodeT 的默认构造函数。为 PQueue 创建适当的默认构造函数,或者为 nodeT 添加用户定义的默认构造函数,以适当地构造 outgoing_arcs

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.

云仙小弟 2024-12-17 00:40:21

如果问题中当前发布的代码是精确副本,则导致此错误的唯一可能原因是 PQueue<...> 未定义默认构造函数,而是定义了另一个构造函数。

否则这段代码会编译。

更准确地说,由于您没有为结构定义构造函数,C++ 会尝试自动生成它们。但它只能做到这一点,只要它的所有成员变量都是适当的默认构造或可初始化的。 std::string 有一个默认的构造函数,而 coordT* 作为一个指针,可以被初始化。因此只有 PQueue<...> 仍然是罪魁祸首。

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.

话少情深 2024-12-17 00:40:21

这可能不是你的问题,但你在 arcT 的这一行上只声明了一个指针:-

nodeT* start, end;

你已经将 start 声明为指针,将 end 声明为实际的 nodeT 对象。这是你想做的吗?

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文