【问题标题】:Static value inheritance [duplicate]静态值继承[重复]
【发布时间】:2015-01-20 15:24:48
【问题描述】:

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

#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

【问题讨论】:

  • 你的意思是“不工作”,也许你可以展示一些真实的代码和输出与预期的输出?
  • "我希望每个类都有自己的静态代码,可以从每个对象请求。"有一种东西叫做虚方法。
  • @Borgleader 这应该是一个答案。
  • @Borgleader 我看不出虚拟成员函数与此有什么关系。这里没有多态性。他所说的“代码”似乎是指一个整数值。
  • 我用一段可编译、可运行的代码更新了我的问题。

标签: c++


【解决方案1】:

您必须将“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;
}

【讨论】:

  • 当值是常量时不需要静态变量(如 OPs cmets 中所述)。
  • @abelenky,你是对的,但我试图给出一个对原始源代码更改较少的解决方案。
  • 如果您不使用指向基类的指针访问子对象(如他的示例中),则不需要虚拟方法,覆盖该方法就足够了。
【解决方案2】:
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;
}

【讨论】:

  • 所以我总是必须为每个类使用一个成员变量?更不用说每次都执行getCode
  • 我认为将静态值放在函数体中更简单。
【解决方案3】:

为什么要使用成员变量?

class Parent {
public:
    static int getCode();
};

int Parent::getCode() {
  return 10;
}

class Child : public Parent {
public:
    static int getCode();
};

int Child::getCode() {
  return 20;
}

每个类都有一个成员函数,而不是每个类一个静态成员。简单明了。

【讨论】:

  • 静态值不是 const,仍然可以更新。但是,您的代码永远不能更改返回代码的值。 (对于海报来说可能没问题......但问题中没有描述)
  • @abelenky 够公平的。
【解决方案4】:

你的问题:

在父类中,您没有将 getCode 函数声明为虚拟函数。 因此,每当您使用继承自父类的类调用它时, 它只会从父类返回 int 代码。

解决这个问题:

  • 首先,在您的父类中将 getCode 函数声明为虚拟函数。
  • 其次,在继承的类中编写另一个 getCode 函数并返回 继承类的 int 代码

【讨论】:

    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多