如何解决构造函数初始化指针数据成员的问题
初始化指针数据成员(即int *顶点)时遇到问题;在构造函数中 参数为int i = 0;如* apex = i; 但不幸的是,在编译器到达这一行之后,什么也没有执行。
<Border Style="{StaticResource BorderWindowStyle}">
<Grid Background="White" />
</Border>
非常感谢 不产生错误
解决方法
您写的等同于:
int *apex;
*apex = 42;
这是未定义的行为(UB),其中包括编译器可能只包含停止执行或开始播放Rick Astley的歌曲Never Gonna Give You Up的代码。
甚至
int *apex = nullptr;
*apex = 42;
将是UB,因为通过int*
取消引用时int
指针必须指向有效的*
只要写
class base{
int apex{};
public:
explicit base(int i) : apex(i){}
};
并为之
,我明白了。相信我,在这个愚蠢的疑问之后,我为自己感到羞耻。
#include <iostream>
using namespace std;
class base{
int *apex;
public:
explicit base(int i = 0){
apex = new int;
// this is what i was supposed to do
*apex = i;
}
};
int main(void){
base test_object(7);
}
,
您的指针指向您未初始化的无效地址 这样可以解决您要求做的事情。
using namespace std;
class base{
int *apex{nullptr};
public:
explicit base(int& i ): apex{&i} {
cout << "this does executes" << endl;
cout << "this doesnt executes" << endl;
}
};
int main(void){
int a = 7
base test_object(a);
cout << "this also doesnt executes";
}
确保为ctor提供的某些内容(int
比实例具有更长的生存期。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。