静态值继承

Static value inheritance

本文关键字:继承 静态      更新时间:2023-10-16

我希望每个类都有自己的静态代码,可以从每个对象请求。我正在考虑这一点,但它似乎不起作用:

#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 代码