[英]C++: how to reuse code in covariant return types?
I have the following simple class 我有以下简单的课程
class base
{
public:
int x;
base &set(int y)
{
x = y;
return *this;
}
};
and want to create a new one with added functionality, say to print the value x. 并希望创建一个具有附加功能的新产品,例如打印值x。 So I do:
所以我做:
class derived : public base
{
public:
void print()
{
cout << x << endl;
}
};
Now in the main program I want to do something like 现在在主程序中,我想做类似的事情
D.set(2).print();
for which however the compiler complains that class base has no member named 'print'. 但是为此,编译器抱怨类库没有名为“ print”的成员。
If I try to use covariant return types and write the two classes as 如果我尝试使用协变返回类型并将两个类写为
class base
{
public:
int x;
virtual base &set(int y)
{
x = y;
return *this;
}
};
class derived : public base
{
public:
derived &set(int y)
{
x = y;
return *this;
}
void print()
{
cout << x << endl;
}
};
then the statement works just fine, but I was forced to rewrite the exact same function body for 'set' in both classes, even though the only thing that changes is the return type. 那么该语句就可以正常工作,但是我不得不在两个类中为“ set”重写完全相同的函数体,即使唯一改变的是返回类型。
If later on I need to change the functionality of base::set then I will have to go through all the derived classes to change the 'set' function... are there any ways to avoid that? 如果以后需要更改base :: set的功能,那么我将必须遍历所有派生类以更改“ set”功能...有什么方法可以避免这种情况? Thanks in advance!
提前致谢!
C++ work as you say, and you say in your base class set
return base&
, so that is what C++ do. C ++就像您说的那样工作,并且您在基类
set
返回base&
,所以C ++就是这样做的。 But in order to solve this you have many ways. 但是为了解决这个问题,您有很多方法。
First you are not forced to make a function virtual
to override it in a derived class (note that virtual call are slightly slower than normal calls). 首先,您不必强制使函数
virtual
以在派生类中重写它(请注意,虚拟调用的速度比普通调用慢一些)。
Second you can refer to base class implementation as base::set
so the code will be as follow: 其次,您可以将基类实现称为
base::set
因此代码如下:
class base {
...
base& set( int x ) {...}
};
class derived : public base {
derived& set( int x ) {
return static_cast<derived&>( base::set(x) );
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.