继承、指针和软件体系结构
Inheritence, pointers and Software Architecture
#include <iostream>
class EquationOfMotion
{
public:
// other attributes
virtual void findNextTimeStep() = 0;
};
class SystemModel
{
public:
EquationOfMotion* p_eom;
// other atributes
SystemModel(EquationOfMotion* new_p_eom)
{
p_eom = new_p_eom;
}
};
class VehicleEquationOfMotion: public EquationOfMotion
{
public:
VehicleEquationOfMotion(...){/* initialise attribute*/}
virtual void findNextTimeStep(){}
};
class Vehicle: public SystemModel
{
// ???? Implementation ?????
}
Vehicle
是SystemModel
的专门化,p_eom
指向VehicleEquationOfMotion
。
我想初始化VehicleEquationOfMotion
的实例,并在Vehicle
中指向它的p_eom
。我希望它只在Vehicle
的范围内定义,同时不使用堆。是否有可能在不使用堆的情况下将VehicleEquationOfMotion
对象驻留在Vehicle
中?(如果没有,请建议设计哪里出了问题)。
可能有帮助:我考虑了这个问题中的实现,但遇到了麻烦(见问题)
如果我答对了你的问题,那么这样做:
class FooChild : public FooParent
{
public:
FooChild (int pX):m_BarChild(pX), FooParent(&m_BarChild) // point p_barPar to instance of BarChild (i.e. m_BarChild)
{
}
private:
BarChild m_BarChild; // instance of BarChild resided in the stack(not the heap) and is local to FooChild
}
如果你想有FooParent。p_barPar要指向驻留在FooChild中的BarChild,您可能需要向FooParent添加默认变量和如下方法:set_p_barPar(BarChild* new_p_bar){p_barPar = new_p_bar;}
。所以你得到:
class FooParent
{
public:
BarParent* p_barPar;
FooParent (){}
FooParent (BarChild* new_p_bar)
{
p_barPar = new_p_bar;
std::cout << p_barPar->x << std::endl;
}
protected:
set_p_barPar(BarChild* new_p_bar)
{
p_barPar = new_p_bar;
}
}
然后你可以实现FooChild:
class FooChild : public FooParent
{
public:
FooChild(int new_x, BarChild* new_p_bar):_bar_child(new_x)
{
set_p_barPar(&_bar_child);
}
private: //? Depends on your plans
BarChild _bar_child();
}
使用类模板
class EquationOfMotion { ... };
template <typename EOM>
class SystemDynamics
{
EOM EquationOfMotion;
...
};
class VehicleEquationOfMotion : public EquationOfMotion { ... };
class Vehicle : public SystemDynamics<VehicleEquationOfMotion> { ... };
也许这就是你想要的。但这种设计并不安全。你正在传递指针给一个未初始化的对象。
class Vehicle: public SystemModel
{
public:
Vehicle(): SystemModel(&_vem)
{
}
VehicleEquationOfMotion _vem;
}
但是,这样做更安全:
class SystemModel
{
public:
EquationOfMotion* p_eom;
// other atributes
SystemModel()
{
}
};
class Vehicle: public SystemModel
{
public:
Vehicle(): SystemModel(&_vem)
{
p_eom = &_vem;
}
VehicleEquationOfMotion _vem;
};
相关文章:
- 如何在 C# 中映射双 C 结构指针?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++:映射结构中的结构指针
- C++:添加新结构时,结构指针向量中的所有元素都会更新
- 体系结构x86_64的未定义符号:std:terminate(),typeinfo,运算符delete[],运算符new
- OSX clang++:用于 cpp 文件中显式实例化模板的体系结构x86_64的未定义符号
- 类的静态结构指针声明在C++
- PCL 出错:体系结构x86_64 @pcl的未定义符号
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 体系结构x86_64的未定义符号:链接器错误
- 在两个.cpp文件之间定义全局类/结构指针
- C++ std::vector<int> 体系结构的未定义符号 x86_64:
- 未使用的 asm() 在不受支持的体系结构上的行为
- 用于本地网络运行的客户端服务器体系结构
- 生成文件:体系结构x86_64的未定义符号
- C 设计用于多层通信的软件体系结构
- C++软件体系结构与设计
- 继承、指针和软件体系结构
- 在哪些体系结构上计算无效指针不安全
- ARM体系结构中的指针处理和Valgrind方法