gpt4 book ai didi

c++ - 将继承与静态函数一起使用

转载 作者:太空狗 更新时间:2023-10-29 22:59:10 27 4
gpt4 key购买 nike

我要设计一个父类

//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 类(class)是这样的

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

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

请帮我解开这个谜题!

最佳答案

听起来你所追求的实际上是一个 virtual static功能。不幸的是,这在 C++ 中不存在。

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

如果您需要静态将一个值从子类传递给它的父类,您可能需要在继承过程中通过模板参数进行传递。

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

class Child : public Parent<5>
{
}

然后Child::getIdSquare()将根据需要返回 25。它无法解决您想要 Parent::getIdSquare 的事实私有(private),同时在 Child 中公开尽管。为此,您需要在 Parent 中将其声明为私有(private)然后在 Child再次声明它是公开的, 实现 return Parent<5>::getIdSquare();

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

关于c++ - 将继承与静态函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37872572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com