search

Home  >  Q&A  >  body text

c++结构体里面的构造函数问题

为什么在结构体里面自己写了个构造函数,被报错了,但是我加上默认形参值就不会报错了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;
const int MAX = 205;
int fa[MAX], r[MAX];
struct EDGE
{
    int from, to;
    double cost;

    EDGE(int a, int b, double c)
    : from(a), to(b), cost(c){}
}edge[MAX * MAX];

这就是代码的声明部分。
下面是报错

但是我给那三个形参赋上默认值,就可以通过编译,请问这是为什么?
代码如下

struct EDGE
{
    int from, to;
    double cost;

    EDGE(int a = 0, int b = 0, double c = 0.0)
    : from(a), to(b), cost(c){}
}edge[MAX * MAX

];

PHP中文网PHP中文网2766 days ago518

reply all(2)I'll reply

  • 阿神

    阿神2017-04-17 13:35:50

    The keywords struct and class in C++ are both used to define classes. Except for the default access qualifier, they are the same in all other aspects. Therefore, classes and structures are collectively referred to as classes below.

    struct EDGE
    {
        int from, to;
        double cost;
    
        EDGE(int a, int b, double c)
        : from(a), to(b), cost(c){}
    }edge[MAX * MAX];  // 这里定义了一个 EDGE 类型的变量数组,由于没有提供参数,数组的每一个元素会调用默认构造函数初始化,而 EDGE 类没有提供默认构造函数,所以会报错。

    But if I assign default values ​​to those three formal parameters, it can be compiled. Why is this?

    This way there is a default constructor, so no error will be reported.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:35:50

    Objects in the array, whether they are class objects (struct or class) or basic data types, if no initialization list is given, value initialization will be performed, that is, the basic data types are initialized to 0, and the class Objects implement a default constructor (i.e. a constructor that does not accept any parameters).
    Because you defined a constructor in the struct you wrote, the compiler will not implicitly declare a default constructor for you , and you defined an array and there is no default constructor , the compiler will report an error.

    reply
    0
  • Cancelreply