C++ 与此一致
我有一个const方法,我想在其中将类B的成员的属性设置为当前实例a(通过指针进行反向引用) A类:C++ 与此一致,c++,constants,const-correctness,C++,Constants,Const Correctness,我有一个const方法,我想在其中将类B的成员的属性设置为当前实例a(通过指针进行反向引用) A类: void A::foo () const { ... ... B b; b.setA(this); ... } B类: setA(A * Ap){ this->pointerToA = Ap; } B * getA() {return pointerToA;} A* pointerToA; setA(const A * Ap){ this-
void A::foo () const
{
...
...
B b;
b.setA(this);
...
}
B类:
setA(A * Ap){
this->pointerToA = Ap;
}
B * getA() {return pointerToA;}
A* pointerToA;
setA(const A * Ap){
this->pointerToA = Ap;
}
const A * getA() {return pointerToA;}
const A* pointerToA;
编译器不允许此操作。。。好啊
现在我试着
B类:
setA(A * Ap){
this->pointerToA = Ap;
}
B * getA() {return pointerToA;}
A* pointerToA;
setA(const A * Ap){
this->pointerToA = Ap;
}
const A * getA() {return pointerToA;}
const A* pointerToA;
这解决了最初的问题,但现在我无法调用B:
...
this->getA()->anotherMethodOfA();
...
因为我得到“无法将'this'指针从'const A'转换为'A&'
虽然我理解上面的问题,但我不知道现在如何调用另一个方法以及问题是什么……为什么在错误消息中有a&呢,因为我没有对a的引用?因为a是一个常量指针,所以只能对其调用
const
方法。有两种可能的解决方案:
void a::foo()const
中删除const
说明符,因为函数实际上是通过对B的调用来修改此
anotherMethodOfA
以及在Bconst
内部调用的任何其他方法如果您需要
foo
成为const
,并且在内部foo
上调用的方法不会以通过公共界面可见的方式对其进行更改(例如,执行一些缓存等),您也可以尝试使用带有修改字段的可变
说明符。但请不要滥用此功能!您可以通过使用Scott Meyers'
解决方案来解决此问题:所有getter的两个版本,一个非常量
版本调用常量
版本,而常量
版本返回e预期变量:
const A* GetA() const { return pointerToA; }
//Cast 'this' to a const reference to B
//(this allows you to call the const version of the getter instead of infinite recursion).
//Cast away the const-ness of the result returned by the const version
//and return the non-const version.
A* GetA() { return const_cast<A*>(static_cast<const B&>(*this).getA()); }
const A*GetA()const{return pointerToA;}
//将“this”强制转换为对B的常量引用
//(这允许您调用getter的const版本,而不是无限递归)。
//丢弃常量版本返回的结果的常量
//并返回非常量版本。
A*GetA(){return const_cast(static_cast(*this).GetA());}
;-)2.帮助。当然,anotherMethodOfA必须是常量,否则对象可以修改。提示:我为此奋斗了几个小时,现在它变得100%清晰了。。。