T0T*_*T0R 9 c++ polymorphism unique-ptr
我想将Particle对象存储在vector对象中,以便稍后可以访问它.这些粒子(Electrons和Protons)继承自Particle包含toString()虚方法的类.toString()然后将此方法覆盖在类Electron和Proton类中.
当我读取向量容器时,我想要访问toString()特定于Electron或的方法Proton,而不是Particle.
显然,一种方法是使用std::unique_ptr.这是我尝试运行的代码的一部分:
int main(){
/**/
std::vector<std::unique_ptr<Particle>> particles(nbParticles);
particles.push_back(std::unique_ptr<Electron>( new Electron(1.0, 2.0, 3.0)));
particles.push_back(std::unique_ptr<Proton>(new Proton(1.0, 2.0, 3.0)));
particles.push_back(std::unique_ptr<Particle>(new Particle(0.0, 0.0, 1.0, 2.0, 3.0)));
if (particles[0]==nullptr){
std::cout<< "index=0 : nullptr"<<std::endl; //There is a null_ptr at particles[0]
}
if (particles[2]==nullptr){
std::cout<< "index=2 : nullptr"<<std::endl; //There is not a null_ptr at particles[2]
}
std::cout<<particles[0]->toString()<<std::endl; //This is what I'm trying to do
/**/
}
Run Code Online (Sandbox Code Playgroud)
指向Particle对象的指针似乎很好,但不是指向Electron或Proton.我猜构造函数有问题吗?
class Particle
{
public:
Particle();
Particle(double mass, double charge, double posX, double posY, double posZ);
virtual std::string toString() const;
}
class Electron : public Particle
{
public:
Electron(double PosX, double PosY, double PosZ);
virtual std::string toString() const;
}
class Proton : public Particle
{
public:
Proton(double PosX, double PosY, double PosZ);
virtual std::string toString() const;
}
Run Code Online (Sandbox Code Playgroud)
和定义:
Particle::Particle(double mass, double charge, double posX, double posY, double posZ) :
m_mass(mass), m_charge(charge),
m_posX(posX), m_posY(posY), m_posZ(posZ) {}
Electron::Electron(double PosX, double PosY, double PosZ) :
Particle(9.109E-31, -1.602E-19, PosX, PosY, PosZ){}
Proton::Proton(double PosX, double PosY, double PosZ) :
Particle(9.109E-31, +1.602E-19, PosX, PosY, PosZ){}
Run Code Online (Sandbox Code Playgroud)
Bri*_*ian 19
你犯了一个经典的错误,即使是最有经验的C++程序员也会绊倒:你用初始大小声明了向量,然后push_back给它添加了额外的元素,而不是分配给现有的元素.通过(nbParticles)从向量初始化中删除来解决此问题.
| 归档时间: |
|
| 查看次数: |
527 次 |
| 最近记录: |