使用继承与静态函数

时间:2016-06-17 03:21:25

标签: c++ inheritance static

我想设计一个父类

//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(),因为它是私人的。我如何继续创造类似的东西。这是一个非工作代码,只是为了说明这个概念。因此,如果我创建另一个子类,我可以在自己的主体中指定索引。我想静态调用该方法。

请帮我弄清楚这个难题!

2 个答案:

答案 0 :(得分:1)

这听起来像你真正的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();

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

答案 1 :(得分:0)

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

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;
     }
};