为什么我不能使对象 m1
Why can I not make the object m1?
我试图创建类'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;
}
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 为什么我不能使对象 m1