如何使用 C++ 中的继承函数访问派生类中的局部变量

How do I access local variables in derived class with inherited functions in C++

本文关键字:派生 局部变量 访问 继承 何使用 C++ 函数      更新时间:2023-10-16

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

我是从 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.  

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

在 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方法,因为您不会重写它,但您应该定义一个虚拟析构函数:何时使用虚拟析构函数?

可以在基类中保护"name"参数,然后在派生类的构造函数中更新其值。

或者,重写基类构造函数以接受字符串,然后通过派生类构造函数传递该字符串。这样,您可以将变量"name"设为私有。