#include<iostream>
using namespace std;
class complex {
public:
complex(double real, double imag);
public:
void display();
private:
double real;
double imag;
};
complex::complex(double real, double imag) :this->real(real), this->imag(imag) {};
void complex::display() {
cout << this->real << this->imag << endl;
}
int main() {
complex c1(5, 2);
complex c2(2, 3);
c1.display();
c2.display();
}
以上构造函数中的this指针是错误的,为什么?
this指针不能用在构造函数吗
去掉 this-> 即可
#include<iostream>
using namespace std;
class complex {
public:
complex(double real, double imag);
public:
void display();
private:
double real;
double imag;
};
complex::complex(double real, double imag) :real(real), imag(imag) {};
void complex::display() {
cout << this->real << this->imag << endl;
}
int main() {
complex c1(5, 2);
complex c2(2, 3);
c1.display();
c2.display();
}
在初始化列表中调用this 需要确保你调用的成员已经被初始化,否则不安全,所以题主的代码里调用this时成员还未被初始化,所以出错,这里把this删除即可。
简单的说:初始化列表中不要使用 this 指针。
解释下:在构造函数中,this指针指向正在被构造的对象,对象还没有完全生成,此时使用this指针是危险的。this指针属于对象,初始化列表在构造函数之前执行。
让我们来看一下【反汇编】代码来探索this指针
对下面的主函数【调试】的时候进行反汇编
int main(void) { Date d1(2016,9,27); system("pause"); return 0; }
结果如下:
也就是【this指针】所指向的内容
问题标题: c++构造函数中使用this指针的错误情况
问题内容: 为什么在以上的C++构造函数中,使用了this指针是错误的?这是因为this指针不能在构造函数中使用吗?请解释原因。
回答: 使用this指针是错误的原因是因为在构造函数中,对象尚未完全创建完成,此时使用this指针可能会引发不可预料的行为。具体原因如下:
this指针指向的是当前正在调用成员函数的对象的地址。在构造函数中,对象尚未完全创建完成,此时调用成员函数使用this指针会导致访问尚未初始化或不一致的成员变量。
构造函数的目的是初始化对象的成员变量,使用this指针可能会导致成员变量的值被修改为不正确的值,从而影响对象的状态和行为。
在构造函数中使用this指针可能会导致编译器警告或错误,提示使用未初始化的变量,这是因为成员变量的初始化在构造函数调用之前完成。
因此,为了避免这些问题,通常在构造函数中不应该使用this指针。可以在构造函数之外的其他成员函数中使用this指针来访问和操作成员变量。