我正在尝试创建类 'cls' 的新对象。我创建了一个无参数构造函数,据我所知,它应该创建一个新对象。但程序崩溃并显示消息 Segmentation Fault Core Dumped 。
但是,如果我取消注释第 13 行 d = new int; 该程序运行良好。
///////////////////////////////////////
#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
你也可以解决你的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句