如何使用基类/继承类的成员函数访问派生类的局部变量?
我从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 {
std::string name = "Parent";
public:
std::string getName() {
return name;
}
};
class StateReading : public State {
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
,因为您没有覆盖任何内容。