我想知道为什么这段代码无法编译并出现错误,指出“函数中的成员标识符意外......”因为“this”指针指向模块本身中声明的单个对象,这使得它在这种情况下就像一个隐藏参数如果类是独立的(即不继承任何其他类的类),则使用“this”是退化的,并且不能对显式使用“this”产生影响。
并且还考虑到使用'this'指向作为指针的属性是非法的(因为编译器抛出错误),为什么编译器只检测用户定义的方法(getdata1(),getdata2(), setdata1(),setdata2()) 并认为构造函数和析构函数没有错误?(嗯,这表明使用“this”来指向作为指针的属性并不是非法的;这个错误背后一定有一些原因。)
class sampclass {
private:
int *data1,*data2;
public:
sampclass(); // constructor
~sampclass(); // destructor
int getdata1() const {
return this->(*data1); // ERROR: Member identifier unexpected in function sampclass::getdata1() const
}
int getdata2() const {
return this->(*data2); // ERROR: Member identifier unexpected in function sampclass::getdata2() const
}
void setdata1(int data) {
this->(*data1)=data; // ERROR: Member identifier unexpected in function sampclass::setdata1(int)
}
void setdata2(int data) {
this->(*data2)=data; // ERROR: Member identifier unexpected in function sampclass::setdata2(int)
}
};
sampclass::sampclass() {
this->data1=new int(0); // assign default value of 0
this->data2=new int(0);
cout << "\nConstruction Successful\n";
}
sampclass::~sampclass() {
delete this->data1;
delete this->data2;
//data1=NULL;
//data2=NULL;
cout << "\nDestruction Successful\n";
}
int main() {
sampclass *obj=new sampclass;
cout << "data1: " << obj->getdata1() << "\ndata2: " << obj->getdata2() << endl;
obj->setdata1(10);
obj->setdata2(99);
cout << "data1: " << obj->getdata1() << "\ndata2: " << obj->getdata2() << endl;
delete obj;
obj=NULL;
cout << "End of program";
return 0;
}
谁能解释一下编译器抛出这个错误的原因?我相信这背后一定有一个解释。请注意,错误作为注释被提及;当从代码中删除所有“this->”时(如预期的那样),总共会抛出 4 个错误,并且程序会根据需要进行编译和运行。
提前致谢。