静态值继承
Static value inheritance
我希望每个类都有自己的静态代码,可以从每个对象请求。我正在考虑这一点,但它似乎不起作用:
#include <iostream>
class Parent {
protected:
static int code;
public:
int getCode();
};
int Parent::code = 10;
int Parent::getCode() {
return code;
}
class Child : public Parent {
protected:
static int code;
};
int Child::code = 20;
int main() {
Child c;
Parent p;
std::cout << c.getCode() << "n";
std::cout << p.getCode() << "n";
return 0;
}
它输出:
10
10
然而我期待
20
10
你必须使'getCode()'函数成为虚拟的,并且每次都必须实现为以下代码:
class Parent {
protected:
static int code;
public:
virtual int getCode() { return code; }
};
int Parent::code = 10;
class Child : public Parent {
protected:
static int code;
public:
virtual int getCode() { return code; }
};
int Child::code = 20;
int main()
{
Child c;
Parent p;
std::cout << c.getCode() << "n";
std::cout << p.getCode() << "n";
return 0;
}
class Parent {
public:
virtual int getCode();
// Looks like a variable, but actually calls the virtual getCode method.
// declspec(property) is available on several, but not all, compilers.
__declspec(property(get = getCode)) int code;
};
class Child : public Parent {
public:
virtual int getCode();
};
int Parent::getCode() { return 10; }
int Child::getCode() { return 20; }
int main() {
Child c;
Parent p;
std::cout << c.code << "n"; // Result is 20
std::cout << p.code << "n"; // Result is 10
return 0;
}
为什么要使用成员变量?
class Parent {
public:
static int getCode();
};
int Parent::getCode() {
return 10;
}
class Child : public Parent {
public:
static int getCode();
};
int Child::getCode() {
return 20;
}
不是每个类有一个静态成员,而是每个类有一个成员函数。 简单明了。
你的问题:
在父类中,您不会将 getCode 函数声明为虚拟函数。 因此,每当使用继承自父类的类调用它时, 它将只从父类返回 int 代码。
要解决此问题,请执行以下操作:
- 首先,在父类中将 getCode 函数声明为虚拟函数。
- 其次,在继承的类中编写另一个 getCode 函数并返回继承类中的 int 代码
相关文章:
- 在类中继承静态变量?
- 如何在复杂继承中访问静态成员变量
- 名称隐藏对静态函数继承的实例使用
- 继承:动态派生类成员与静态派生类成员
- 使用 CRTP 进行选择性静态成员继承
- 模板,继承,静态成员增量
- 公共继承的静态断言
- 静态变量继承C++
- 在C 中,静态成员函数是否继承了?如果是,为什么没有出现歧义错误
- 类继承中的静态内联
- 如何定义从虚拟函数继承的静态函数
- 如果基类是公开继承的,那么基类的公共静态函数是否会成为派生类的成员函数
- 将继承与静态函数结合使用
- 具有静态属性(服务定位器模式)的模板继承
- C++:从静态方法调用继承的静态方法
- 如何继承静态成员
- 静态成员继承和保护
- 继承类型的指针之间的静态强制转换
- 为什么重载的继承静态函数不明确
- 模板类:未继承静态成员