为什么我不能使对象 m1

Why can I not make the object m1?

本文关键字:对象 m1 不能 为什么      更新时间:2023-10-16

我试图创建类'cls'的新对象。我做了一个无参数构造函数,据我所知,它应该创建一个新对象。但是程序崩溃并显示一条消息 分段故障核心转储 .

但是,如果我取消注释第 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指向一个未知的地址,所以有时它不会崩溃,你最好像这样编码:

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