【发布时间】:2020-09-02 12:50:25
【问题描述】:
我在初始化指针数据成员时遇到问题,即 int* apex;在构造函数内部 参数为 int i = 0;如*顶点 = i; 但不幸的是,编译器敲击这一行后没有执行任何操作。
#include <iostream>
using namespace std;
class base{
int *apex;
public:
explicit base(int i = 0){
cout << "this does executes" << endl;
*apex = i; // <<<<<--- problem???
cout << "this doesnt executes" << endl;
}
};
int main(void){
base test_object(7);
cout << "this also doesnt executes";
}
// I know how to avoid this but i want to know what
// exactly the problem is associated with *apex = i;
提前致谢 注意-没有产生错误
【问题讨论】:
-
您永远不会将指针初始化为指向有效内存。所以
*apex调用未定义的行为 -
这与构造函数或类无关。它与取消引用未初始化的指针有关。
-
只能在构造函数的初始化列表中初始化成员变量。你在做的是赋值,你不是在赋值给指针,而是给一些不存在的东西。
标签: c++ class pointers constructor