|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 Croper 于 2018-12-17 20:28 编辑
比如说定义一个myrect类
- class myrect
- {
- public:
- int left;
- int right;
- int top;
- int bottom;
- int centreX()
- {
- return (left + right) / 2;
- }
- void SetCentreX(int x)
- {
- int width = right - left;
- left = x - width / 2;
- right = x + width / 2;
- }
- };
复制代码
类里的数据成员只有left,right,top,bottom,这个时候定义了一个成员函数centreX,但是想要centreX能像成员函数一样执行执行A.centreX()=1;之类的操作是肯定不能打到想要的效果的。。我现在唯一想到的办法只有centreX申明成另外一个类来实现
- class myRectPosX
- {
- friend class myRect;
- private:
- myRect* p;
- public:
- operator int();
- myRectPosX& operator=(int x);
- };
- class myRect
- {
- public:
- int left;
- int right;
- int top;
- int bottom;
- myRectPosX centreX;
- myRect()
- {
- centreX.p = this;
- }
- };
- myRectPosX::operator int()
- {
- return (p->left + p->right) / 2;
- }
- myRectPosX& myRectPosX::operator=(int x)
- {
- int width = p->right - p->left;
- p->left = x - width / 2;
- p->right = x + width / 2;
- return *this;
- }
复制代码
但是这样如果有很多想要这样操作的就要额外申明很多这样的辅助类。。有没有什么更简单的办法呢?
|
|