C ++默认构造函数缺少,我无法编译 [英] C++ default constructors absence and I cannot compile

查看:100
本文介绍了C ++默认构造函数缺少,我无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个非常简单的类

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) {};
};



如果省略行 myclass()= default; / code>,然后尝试创建一个对象。

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;
}

我收到一个错误 '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.

推荐答案

一旦你提供了任何构造函数,你 - 你完全控制。因此,当你有一个需要一些参数,没有参数的那个不再提供。

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.

这篇关于C ++默认构造函数缺少,我无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆