我似乎无法找到任何涉及此类操作的内容。
我有一个class TextButton : public TextDecorator
类,我想重载隐式转换运算符。 TextButton
类包含我想要访问的BasicButton
指针。
重载TYPE转换运算符可以正常工作,但是当我使用TextButton*
执行强制转换时,它无法执行我想要的操作。
此代码显示我的意思:
#include <iostream>
using std::cout;
using std::endl;
class A {
public :
void DoThis() {cout << "a is " << this << endl;}
};
class B {
A* a;
public :
B() : a(new A) {
cout << "a is " << a << endl << endl;
}
~B() {delete a;}
operator A*() {return a;}
};
int main(int argc , char** argv) {
B b;
A* a1 = (A*)b;/// Implicit conversion works fine for objects of type B
A* a2 = (A*)&b;/// Implicit conversion works, but is incorrect for objects of type B*
A* a3 = static_cast<A*>(b);/// Fine, not what I want
/// A* a4 = static_cast<A*>(&b);/// What I want, but illegal
/// "invalid static cast from B* to A*"
a1->DoThis();
a2->DoThis();
a3->DoThis();
/// a4->DoThis();
return 0;
}
输出((un)幸运的是它没有崩溃)显示它为什么不好:
c:\ctwoplus\progcode\test\Cast>cast.exe
a is 0xea1718
a is 0xea1718
a is 0x61ff20
a is 0xea1718
所以我想要的是让这成为可能:
TextButton* tb = MakeTextButton(...);
BasicButton* button_access = (BasicButton*)tb;
让它正常工作。
想法?