C++ default constructors absence and I cannot compile

∥☆過路亽.° 提交于 2019-12-04 05:57:01

问题


I have this very simple class

class myclass {

public:
    int id;
    double x, y, z;

    myclass() = default; // If I omit this line I get an error
    myclass(int ID, double X, double Y, double Z): id(ID), x(X), y(Y), z(Z) {};
};

If I omit the line with the line myclass() = default; and then attempt at creating one object

#include <vector>
using namespace std;
int main() {

    int ID = 0;
    double X = 1.0, Y = 2.0, Z = 3.0;
    vector<myclass> a_vector(10);

    myclass an_object(ID,X,Y,Z);

    return 0;
}

I get an error no matching function for call to ‘myclass::myclass().

Why does this happen? When is it mandatory to specify the constructor taking no parameter as default?

This is probably a very easy question, but other questions on constructors seemed aimed at very specific issues with constructors, so I thought it might be worthwhile.


回答1:


Once you provide any constructor(s), the compiler stops providing other ones for you - you become in full control. Thus when you have one that takes some parameters, the one that takes no parameters is not provided anymore.




回答2:


The problem is in the vector of myclass - vector has many methods that will use the default constructor. If you provide your own constructor as you did, the usual default constructor does not get generated for you. By adding the declaration with = default, you forced the compiler to generate the missing default. You could also define your own default constructor if the automatically generated one isn't sufficient, but there's no way to use a vector without one.




回答3:


because you didn't specify access modifiers for the second constructor, so it's private by default

simply add public: to your constructors

class myclass
{

int id;
double x, y, z;

public:

//myclass() = default; // If I omit this line I get an error
myclass(int ID, double X, double Y, double Z): id(ID), x(X), y(Y), z(Z) {};

};


来源:https://stackoverflow.com/questions/31820235/c-default-constructors-absence-and-i-cannot-compile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!