如何使用 C++ 中的继承函数访问派生类中的局部变量
How do I access local variables in derived class with inherited functions in 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.
对此有什么想法吗? 似乎必须重写每个派生类才能获得本地实例变量将是一场真正的维护噩梦。
在 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"设为私有。
相关文章:
- 使用的未初始化局部变量'Quick'
- 修复未初始化的局部变量错误
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- Gnuplot_i.hpp C++接口绘制局部变量而不是文件
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- C++中静态方法的局部变量范围
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- 离开范围后如何保护局部变量的值?
- 局部变量名称冲突
- C++ lambda:如何'freeze'局部变量的值?
- 我应该使我的局部变量常量还是可移动的
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 返回对局部变量 - C++ 的引用
- 是否可以影响 C++ 中回调函数的局部变量?
- 警告 C4101 未引用的局部变量
- 当类型为shared_ptr<base_type>时,在"局部变量"窗口中将本地作为派生类型查看