为什么我不能制作对象 m1?

Why can I not make the object m1?

我正在尝试创建 class 'cls' 的新对象。我创建了一个无参数构造函数,据我所知,它应该创建一个新对象。但是程序崩溃并显示消息 Segmentation Fault Core Dumped .

但是如果我取消注释第 13 行 d = 新整数; 该程序运行良好。

///////////////////////////////////

#include <iostream>
#include <vector>

using namespace std;
class cls
{
    private:
        int *d;
    public:
        cls() {}   //no args ctor
        cls(int a)     //1 arg ctor
        {
            //d = new int;
            *d = a;
        }
};

int main()
{
    cls m{10};
    cls m1;
    cout<<"Testing if program is still fine"<<endl;
    return 0;
}

*d = a; 很可能会导致崩溃,因为 d 没有指向任何有效的东西(它还没有被初始化)。

为什么 d 首先甚至是一个指针?如果你只是让它成为一个普通的 int 你也解决了你的问题。

d是一个指针,但是没有在cls(int a)处初始化,d指向一个未知的地址,所以有时候不会crash,最好自己写代码像这样:

#include <iostream>
#include <vector>

using namespace std;
class cls
{
    private:
        int d;
    public:
        cls() {}   //no args ctor
        cls(int a)     //1 arg ctor
        {
            d = a;
        }
};

int main()
{
    cls m{10};
    cls m1;
    cout<<"Testing if program is still fine"<<endl;
    return 0;
}