将继承与静态函数结合使用



我想设计一个父类

//Parent.h
class Parent {
private:
int currentId;
static int getIdSquare(); //Just random function for simplicity
}
//Parent.cpp
#include "Parent.h"
int Parent::getIdSquare() { return this->currentId * this->currentId };

当然,这是行不通的!因为你不能在静态函数中访问非静态变量,但要坚持下去。 我希望我的孩子班级是这样的

//Child.h
#include "Parent.h"
class Child : public Parent {
private:
static int index;
};
//Child.cpp
#include "Child.h"
int Child::index = 5;

所以当我打电话给Child::getIdSquare();时,我主要会得到 25。我不应该打电话给Parent::getIdSquare()因为它是私人的。我如何继续创建类似的东西。这是一个非工作代码,只是为了说明这个概念。因此,如果我创建另一个子类,我可以在其自己的主体中指定索引。我想静态调用该方法。

请帮我弄清楚这个难题!

听起来你所追求的确实是一个virtual static函数。 不幸的是,这在C++中不存在。

此外,Child::getIdSquare()也将是私有的,并且在 main() 中无法访问。

如果需要将值从子类静态传递到其父类,则可能需要在继承期间通过模板参数执行此操作。

template <int id>
class Parent
{
public:
static int getIdSquare() { return id * id; }
}
class Child : public Parent<5>
{
}

然后Child::getIdSquare()将根据需要返回 25。 它并没有回避您希望Parent::getIdSquare是私有的这一事实,同时在Child中将其公开。 为此,您需要在Parent中将其声明为私有,然后在Child再次将其声明为公共,并实现return Parent<5>::getIdSquare();

仍然不理想,但这是一个相对模糊的问题,很难在这里真正找到完美的解决方案......

我不确定我是否完全理解这个问题,但我看到了两种选择。如果要实现特定于类型的属性,则可以使用特征:

template<typename T>
struct Square {};
class Parent {
};
class Child: public Parent {};
template<> Square<Parent> {
};
template<> Square<Child> {
static constexpr int getIdSquare() {
return 25;
}
};
void foo() {
// this will not compile
//auto id = Square<Parent>::getIdSquare();
// but this will
auto id = Square<Child>::getIdSquare();
}

另一种设计是使用模板方法模式,但这使用动态调度。它看起来像这样:

class Parent {
public:
int getSquareId() {
return currentId() * currentId();
}
private:
virtual int currentId() = 0;
};
class Child: public Parent {
private:
virtual int currentId() override {
return 5;
}
};

最新更新