1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C++ 不能使用默认构造函数的情况

C++ 不能使用默认构造函数的情况

时间:2022-12-28 14:59:51

相关推荐

C++ 不能使用默认构造函数的情况

C++不能使用默认构造函数是因为,struct或者class没有默认的构造函数。

当程序员定义了自己的构造函数的时候,默认构造函数会失效。如果这个时候想要默认的构造函数,在struct或者class里面加一个空的构造函数就可以了。

报错的完整代码如下:

#include <iostream>using namespace std;#define MaxRouterNum 100typedef struct ArcNode {int routerId;int routerMetrix;struct ArcNode* next;}ArcNode;typedef struct VNode {int routerId;struct ArcNode* first;int netPrefix;int netMetric;VNode(int routerI, int netPre, int netM){routerId = routerI;first = nullptr;netPrefix = netPre;netMetric = netM;}}VNode, AdjList[MaxRouterNum];typedef struct Graph {int routerVexNum;int ruonterArcNum;AdjList vertices;}Graph;int main() {Graph graph;graph.routerVexNum = 4;graph.ruonterArcNum = 4;}

报错出现在main函数中的Graph graph。经检查发现,Graph中并没有定义自己的构造函数,那为什么默认的构造函数会失效呐?

原来是因为Graph中有AdjList vertices这句话。而AdjList中定义了自己的构造函数,因此AdjList没有默认的构造函数。只需要在AdjList中加一个空的构造函数就不会出错了。

修改之后的代码如下:

#include <iostream>using namespace std;#define MaxRouterNum 100typedef struct ArcNode {int routerId;int routerMetrix;struct ArcNode* next;}ArcNode;typedef struct VNode {int routerId;struct ArcNode* first;int netPrefix;int netMetric;VNode(int routerI, int netPre, int netM){routerId = routerI;first = nullptr;netPrefix = netPre;netMetric = netM;}VNode() {}}VNode, AdjList[MaxRouterNum];typedef struct Graph {int routerVexNum;int ruonterArcNum;AdjList vertices;}Graph;int main() {Graph graph;graph.routerVexNum = 4;graph.ruonterArcNum = 4;}

相关链接:

1

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。