C ++隐式转换运算符 [英] C++ Implicit Conversion Operators

查看:137
本文介绍了C ++隐式转换运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C ++中找到一个好的继承解决方案。



我有一个Rectangle类和一个Square类。 Square类不能从Rectangle公开继承,因为它不能完全满足矩形的要求。例如,一个矩形可以有它的宽度和高度每个单独设置,这当然是不可能与一个正方形。



所以,我的困境。 Square显然会与Rectangle共享大量代码;它们非常相似。



例如,如果我有一个函数:

  bool IsPointInRectangle(const Rectangle& rect); 

它应该适用于一个正方形。事实上,我有很多这样的函数。



所以在做我的Square类,我想我将使用私有继承与公共可访问的矩形转换运算符。所以我的正方形类看起来像:

 类Square:private Rectangle 
{
public:
operator const Rectangle&()const;
};然而,当我尝试传递一个方形到IsPointInRectangle函数,我的编译器只是抱怨矩形是一个无法进入的基地。我希望它注意到Rectangle运算符,并改用它。



我想要做什么?



如果这不能工作,我可能会将Rectangle的一部分重构为 MutableRectangle 类。



谢谢。

解决方案

。看起来私下继承A类阻止你在类外使用运算符A.



你可以通过将一个成员Rectangle用于正方形并使用它来解决你的问题:

  class Square {
Rectangle r;
public:
operator const Rectangle&()const {
return r;
}
};

这应该编译和工作。我相信它不会给你更多的工作,如果有的话。


I'm trying to find a nice inheritance solution in C++.

I have a Rectangle class and a Square class. The Square class can't publicly inherit from Rectangle, because it cannot completely fulfill the rectangle's requirements. For example, a Rectangle can have it's width and height each set separately, and this of course is impossible with a Square.

So, my dilemma. Square obviously will share a lot of code with Rectangle; they are quite similar.

For examlpe, if I have a function like:

bool IsPointInRectangle(const Rectangle& rect);

it should work for a square too. In fact, I have a ton of such functions.

So in making my Square class, I figured I would use private inheritance with a publicly accessible Rectangle conversion operator. So my square class looks like:

class Square : private Rectangle
{
    public:
        operator const Rectangle&() const;
};

However, when I try to pass a Square to the IsPointInRectangle function, my compiler just complains that "Rectangle is an inaccessible base" in that context. I expect it to notice the Rectangle operator and use that instead.

Is what I'm trying to do even possible?

If this can't work I'm probably going to refactor part of Rectangle into MutableRectangle class.

Thanks.

解决方案

Well, I'm surprised. It seems privately inheriting a class A prevents you from using operator A outside the class.

You can solve your problem by making a member Rectangle for square and using it for the cast:

class Square {
    Rectangle r;
    public:
        operator const Rectangle&() const {
            return r;
        }
};

This should compile and work. And I believe it won't give you that much more work to do if any.

这篇关于C ++隐式转换运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆