我想将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 …Run Code Online (Sandbox Code Playgroud) 我想在游戏中实现物理引擎,以便计算施加力的物体的轨迹.该引擎将根据其先前的状态计算对象的每个状态.当然,这意味着两个时间单位之间的大量计算足够精确.
为了做到这一点,我首先要知道这种获取位置的方法与运动方程之间的差异有多大.所以我制作了这个代码,用于存储模拟给出的位置(x,y,z)和文件中的等式.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "header.h"
Body nouveauCorps(Body body, Vector3 force, double deltaT){
double m = body.mass;
double t = deltaT;
//Newton's second law:
double ax = force.x/m;
double ay = force.y/m;
double az = force.z/m;
body.speedx += ax*t;
body.speedy += ay*t;
body.speedz += az*t;
body.x +=t*body.speedx;
body.y +=t*body.speedy;
body.z +=t*body.speedz;
return body;
}
int main()
{
//Initial conditions:
double posX = 1.4568899;
double posY = 5.6584225;
double posZ = -8.8944444;
double speedX = 0.232323;
double …Run Code Online (Sandbox Code Playgroud)