使用同一类中的方法重新分配字段时出现问题



我正在为分子动力学模拟开发相对基本的代码,我决定第一次尝试混合一些OOP。我的类P包含粒子的基本场(质量、位置和速度(,我将为特定的潜在函数(如 Lennard-Jones(生成派生类。

我在setSpecies函数方面遇到了一个问题;我的目标是能够通过一个物种的化学式或名称,并自动设置质量。但是,我似乎无法更改m的值,除了像我将其设置为等于 7 一样这样做:

噗嗤

#ifndef P_H_
#define P_H_
#include <string>
#include <vector>
using namespace std;
struct P {
static int N; // total number of particles
int n; //particle number
double m; //mass
void setSpecies(string species);
P();
};
#endif

P.cpp

#include "P.h"
#include <algorithm/string/predicate.hpp>
#include <iostream>
using boost::algorithm::iequals;
using namespace std;
void P::setSpecies(string species){
if (boost::iequals(species,"argon") || boost::iequals(species,"Ar")){
m = 6.6335209e-26; //no good
}
else
m = 0.0; // no good
//m = 7.0; // this one works when not commented
};
P::P() {
m = 0.0;
n = N++;
};

即使尝试在 main(( 中重新分配值也不会执行任何操作:

P atom[10];
for (int i = 0; i < 10; i++){
atom[i].setSpecies("Ar"); \ no good
atom[i].m = 4.0; \ no good
}

我的猜测是它必须对数组中的对象做一些事情,或者我正在使用boost,但我没有得到任何编译或运行时错误。我错过了什么?

如果你忽略你的类并提升你的代码,归结为:

double m;
if (condition){
m = 6.6335209e-26;
}
else{
m = 0.0;
}
m = 7.0;

无论condition是什么,ifelse语句中设置的值都会被m = 7.0覆盖。

最新更新