我正在学习 C++。我写了一个小程序来计算能量 N粒子系统到目前为止,我有三个小文件:
数据.h:
class Particle {
public:
double mass;
double charge;
double posx,posy,posz;
};
Particle part[2];
主要.cpp:
#include <iostream>
#include "data.h"
using namespace std;
double energy(Particle part );
int main ()
{
double sd;
part[0].mass = 10.0;
part[4].mass = 90.0;
cout << part[0].mass << "\n";
cout << part[4].mass << "\n";
sd = energy(part);
cout << "sd" << sd << "\n" ;
return 0;
}
能量.cpp:
#include <iostream>
using namespace std;
double energy(Particle part)
{
cout << part[0].mass << "\n";
double dummy;
dummy = 2.0;
return (dummy);
}
我有两个问题:
1)我想让函数“能量”中的类粒子可见。换句话说, 我想使用类函数的变量(具有“main”中给出的值) 在能量函数中。 我已经尝试过你看到的能量(粒子部分)但似乎没有定义粒子 在那个范围内。
2) 正如您在“data.h”中所见,我将“part”声明为具有两个成员的数组。然而, 在“main”中我可以使用两个以上的成员,例如 part[3]、part[4]... 为什么我 可以使用比我声明的更多的成员吗?
我正在用 g++ -o test energy.cpp main.cpp 编译
谢谢。
最佳答案
1)I want to make visible the Class particle in the function "energy". In other words, I want to use the variables of the class function (with the values given in "main") in the energy function. I have tried as you see energy(Particle part) but it seems Particle is not defined in that scope.
如果我没理解错的话..你想要
Particle part[2];
可以在 main.cpp 和 energy.cpp 中使用吗? 如果是.. 将其更改为:
extern Particle part[2];
并在 energy.cpp 中添加:
#include "data.h"
Particle part[2];
你将能够使用
double energy()
{
//main.cpp will have same part
cout << part[0].mass << "\n";
double dummy;
dummy = 2.0;
return (dummy);
}
2)As you see in "data.h" I declared "part" as an array with two members. However, in "main" I can use more than two members, for instance part[3],part[4]... Why I could use more members than those I declared?
因为它是 C/C++?没有范围检查。你想做什么,就可以做什么。 但如果这样做,结果将是意想不到的。
关于c++ - 类成员和函数c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7691452/