C++问题:使用派生类进行类提升
我有一个从 Float32_base 派生的 Float32 类。
class Float32_base { public: // Constructors Float32_base(float x) : value(x) {}; Float32_base(void) : value(0) {}; operator float32(void) {return value;}; Float32_base operator =(float x) {value = x; return *this;}; Float32_base operator +(float x) const { return value + x;}; protected: float value; } class Float32 : public Float32_base { public: float Tad() { return value + .01; } } int main() { Float32 x, y, z; x = 1; y = 2; // WILL NOT COMPILE! z = (x + y).Tad(); // COMPILES OK z = ((Float32)(x + y)).Tad(); }
问题是 + 运算符返回 Float32_base 而 Tad() 不在该类中。但'x'和'y'是Float32的。
有没有一种方法可以让我在第一行中编译代码,而不必像在下一行中那样求助于类型转换?
I have a class for Float32 that is derived from Float32_base
class Float32_base { public: // Constructors Float32_base(float x) : value(x) {}; Float32_base(void) : value(0) {}; operator float32(void) {return value;}; Float32_base operator =(float x) {value = x; return *this;}; Float32_base operator +(float x) const { return value + x;}; protected: float value; } class Float32 : public Float32_base { public: float Tad() { return value + .01; } } int main() { Float32 x, y, z; x = 1; y = 2; // WILL NOT COMPILE! z = (x + y).Tad(); // COMPILES OK z = ((Float32)(x + y)).Tad(); }
The issue is that the + operator returns a Float32_base and Tad() is not in that class. But 'x' and 'y' are Float32's.
Is there a way that I can get the code in the first line to compile without having to resort to a typecast like I did on the next line?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您只需要一级深度继承,您可以使用 CRTP:
You can use CRTP if you only need one-level deep inheritance:
您必须重写operator+方法,因为operator+的返回类型被定义为Float32_base。您可以通过协方差来做到这一点并使该方法成为虚拟的。然后重写子类中的方法(您可能只调用超类中的方法)。
您也可以通过模板来完成此操作,但如果您不熟悉模板,我不建议深入研究它。本质上,您可以按照已经定义的方式定义虚拟函数,但不是返回 Float32_base,而是返回模板类型。 (只要你的模板类型是子类,那么 C++ 应该具有良好的逆变性)。您的子类将使用子类的模板扩展基类。
You have to override the operator+ method since your return type for operator+ is defined as Float32_base. You can do this through covariance and make the method virtual. Then override the method in your subclass (you could probably just call the method in the superclass).
You could also do this through Templates, but if you're not familiar with Templates I wouldn't suggest digging into it. Essentially you would define the virtual function the way you already did but instead of returning Float32_base, you would return your template type. (as long as your template type is a subclass then C++ should be good with contravariance). Your subclass would extend the baseclass with a template of the subclass.
您可以根据操作的结果类型模板化
FLoat32_base
类。或者将所有内容放入一个类中(可能是最好的),将少数特定于平台的操作委托给特定于平台的功能。
干杯&呵呵,
You can template the
FLoat32_base
class on the result type of operations.Or put everything into a single class (probably best), delegating the few platform-specific operations to platform specific functions.
Cheers & hth.,