64,518
社区成员
发帖
与我相关
我的任务
分享
typedef struct B
{
int i;
float f;
};
class CA
{
public:
//重载operator ->();
void Method(void);
B& b;
};
void main()
{
CA *a;
//如何重载操作符-> 可以在使用下面的用法编辑通过,有没人指点下啊,就是说令->的返回具能是结构体的引用,又能代表类的this指针.
a->i;
a->Method();
}
为什么将B结构体的定义放在外面的,
你那样子能够实现吗?
我觉得使用Pimpl手法,比较适合的,
template<class _Ty>
class auto_ptr
{ // wrap an object pointer to ensure destruction
public:
typedef _Ty element_type;
explicit auto_ptr(_Ty *_Ptr = 0)
: _Myptr(_Ptr)
{ // construct from object pointer
}
auto_ptr(auto_ptr<_Ty>& _Right)
: _Myptr(_Right.release())
{ // construct by assuming pointer from _Right auto_ptr
}
template<class _Other>
operator auto_ptr<_Other>()
{ // convert to compatible auto_ptr
return (auto_ptr<_Other>(*this));
}
auto_ptr<_Ty>& operator=(auto_ptr<_Ty>& _Right)
{ // assign compatible _Right (assume pointer)
reset(_Right.release());
return (*this);
}
~auto_ptr()
{ // destroy the object
delete (_Ty *)_Myptr;
}
// 返回引用
_Ty& operator*() const
{ // return designated value
return (*(_Ty *)_Myptr);
}
// 返回封装的对象的指针
_Ty *operator->() const
{ // return pointer to class object
return (&**this); // 第二个*由auto_ptr的指针得到当前对象,第一个*调用当前对象的的operator*()
}
_Ty *get() const
{ // return wrapped pointer
return ((_Ty *)_Myptr);
}
_Ty *release()
{ // return wrapped pointer and give up ownership
_Ty *_Tmp = (_Ty *)_Myptr;
_Myptr = 0;
return (_Tmp);
}
void reset(_Ty* _Ptr = 0)
{ // destroy designated object and store new pointer
if (_Ptr != _Myptr)
delete (_Ty *)_Myptr;
_Myptr = _Ptr;
}
private:
const _Ty *_Myptr; // the wrapped object pointer
};