如何在 C++ 中从基 class 和 return 派生 class 继承后记增量
How to inherit postscript increment from base class and return derived class in c++
我有几个具有类似行为的 c++ classes。此外,大多数 class 方法都可以从几个基本方法中构建出来。所以我想用派生方法定义一个基础class,从基础class继承并在派生class中定义剩余的方法。
这是我尝试使用 CRTP
template <class derived_class> class base_class {
public:
virtual derived_class& operator++ () = 0;
virtual derived_class& fun1() = 0;
derived_class operator++ (int) {
derived_class toreturn(static_cast<derived_class&>(*this));
++*this;
return toreturn;}
derived_class& fun2() {
this->fun1();
return static_cast<derived_class&>(*this);
};
};
class deriv1 : public base_class<deriv1> {
public:
int n;
deriv1():n(0){};
deriv1(deriv1& other):n(other.n){};
deriv1& operator++ () override { ++n; return *this;}
deriv1& fun1() override { n *= n; return *this;}
};
我不明白为什么 fun2() 有效但 postscript 增量无效。
如果我在派生对象上调用后记增量,我会收到错误消息“无法增加类型 'deriv1'”的值。
解决方法是添加一条using语句:
class deriv1 : public base_class<deriv1> {
public:
....
using base_class::operator++;
};
问题是函数解析失败。让我们想一个更简单的解决方案来说明问题:
struct Base
{
void f() {}
void f(int) {}
};
struct Derived: public Base
{
void f() {}
};
int main()
{
Derived a;
a.f(1); // This fails as there is no f() that takes an integer
// in Derived. And since the compiler found an f() in
// Derived it stopped looking further up the chain
// for additional matches.
}
本题同法解决
struct Derived: public Base
{
using Base::f;
void f() {}
};
我有几个具有类似行为的 c++ classes。此外,大多数 class 方法都可以从几个基本方法中构建出来。所以我想用派生方法定义一个基础class,从基础class继承并在派生class中定义剩余的方法。 这是我尝试使用 CRTP
template <class derived_class> class base_class {
public:
virtual derived_class& operator++ () = 0;
virtual derived_class& fun1() = 0;
derived_class operator++ (int) {
derived_class toreturn(static_cast<derived_class&>(*this));
++*this;
return toreturn;}
derived_class& fun2() {
this->fun1();
return static_cast<derived_class&>(*this);
};
};
class deriv1 : public base_class<deriv1> {
public:
int n;
deriv1():n(0){};
deriv1(deriv1& other):n(other.n){};
deriv1& operator++ () override { ++n; return *this;}
deriv1& fun1() override { n *= n; return *this;}
};
我不明白为什么 fun2() 有效但 postscript 增量无效。 如果我在派生对象上调用后记增量,我会收到错误消息“无法增加类型 'deriv1'”的值。
解决方法是添加一条using语句:
class deriv1 : public base_class<deriv1> {
public:
....
using base_class::operator++;
};
问题是函数解析失败。让我们想一个更简单的解决方案来说明问题:
struct Base
{
void f() {}
void f(int) {}
};
struct Derived: public Base
{
void f() {}
};
int main()
{
Derived a;
a.f(1); // This fails as there is no f() that takes an integer
// in Derived. And since the compiler found an f() in
// Derived it stopped looking further up the chain
// for additional matches.
}
本题同法解决
struct Derived: public Base
{
using Base::f;
void f() {}
};