首页 > 解决方案 > 如何使用 C++ 中的继承函数访问派生类中的局部变量

问题描述

如何使用基类/继承类的成员函数访问派生类的局部变量?

我是从 JavaScript 的角度来的,虽然我有一些 Java 经验,但已经有一段时间了。这是 JavaScript 中期望的结果。

// JavaScript Example

class State {
    constructor(name){
        this.name = name || "Parent";
    }

    getName(){ return this.name };
}

class StateReading extends State {
    constructor(){
        super("Child");
    }

    // Since StateReading extends State, it also inherits its parent's functions
    // in this case, it inherits getName()

}

const s = new StateReading();
console.log(s.getName());   // I print out "Child"

我正在尝试用 C++ 实现类似的东西,但是我有很长时间让所有的位(har har)排成一行。

#include <iostream>
using namespace std;


 class State {
    std::string name = "Parent";

    public: 
        virtual std::string getName() {  // "virtual" keywords removes the compile time linkage
            return name;
        }
 };

 class StateReading : public State {
     std::string name = "Child";
 };


int main() {

    StateReading sr = StateReading();
    State* s = &sr;  // Make state a pointer to a memory address so it can be reused

    cout<<s -> getName(); // Prints "Parent" ... but I'm pointing to StateReading's memory address ... :/
    cout<<sr.getName(); // At least this one should be child ... wait, it's "Parent" too?!
    return 0;
}

我可以让它工作的唯一方法是在子类中覆盖 getName() 。但我真的不想重写子类中的每一个方法。我正在尝试使用工厂模式来处理多态性的概念。我知道我总是会创建某种“状态”,但它可以是许多派生类中的任何一个。

// Untested example
class StateFactory{

  public: 
    static make(params){
        switch(params) {
            case 0: return StateReading();
            case 1: return StatePaused();
            case 2: return StateWriting();
            default: // etc.
        }
    }
}


State state = StateFactory.make(params);
state.getName();  // prints out the state's name.  

对此有什么想法吗?似乎必须重写每个派生类才能获取本地实例变量将是真正的维护噩梦。

标签: c++inheritancepolymorphism

解决方案


在 JS 中,您调用基类的构造函数。在 C++ 中做同样的事情

#include <iostream>
using namespace std;


 class State {
 public:
    State() = default;
    State(const std::string &n) : name(n) {}
    virtual ~State() = default;

    std::string getName() {
        return name;
    }
 private:
    std::string name = "Parent";
 };

 class StateReading : public State {
 public:
     StateReading() : State("Child") {}
 };


int main() {

    StateReading sr = StateReading();
    State* s = &sr;  // Make state a pointer to a memory address so it can be reused

    cout<<s -> getName(); // Prints "Parent" ... but I'm pointing to StateReading's memory address ... :/
    cout<<sr.getName(); // At least this one should be child ... wait, it's "Parent" too?!
    return 0;
}

您不需要virtual方法,因为您没有覆盖它,但您应该定义一个虚拟析构函数:何时使用虚拟析构函数?


推荐阅读