C++ 从文件创建类

C++ 从文件创建类,c++,C++,我不太明白为什么我的程序会打印出奇怪的数字,我相信是地址号…我试图从一个文件中读取数据,然后将它们存储在类实例中…该文件的id,x,y,z在一行中…它有10行,因此我必须创建10个类实例…非常高兴您的帮助^^ class planet { public: int id_planet; float x,y,z; }; void report_planet_properties(planet& P) { cout<<"Planet's ID: "<

我不太明白为什么我的程序会打印出奇怪的数字,我相信是地址号…我试图从一个文件中读取数据,然后将它们存储在类实例中…该文件的id,x,y,z在一行中…它有10行,因此我必须创建10个类实例…非常高兴您的帮助^^

class planet
{
public:
    int id_planet;
    float x,y,z;
};

void report_planet_properties(planet& P)
{
    cout<<"Planet's ID: "<<P.id_planet<<endl;
    cout<<"Planet's coordinates (x,y,z): ("<<P.x<<","<<P.y<<","<<P.z<<")"<<endl;
}

planet* generate_planet(ifstream& fin)
{
    planet* p = new planet;
    fin >> (*p).id_planet;
    fin >> (*p).x;
    fin >> (*p).y;
    fin >> (*p).z;
    return (p);
}

int main()
{
    planet* the_planets[10];
    int i=0;
    ifstream f_inn ("route.txt");
    if (f_inn.is_open())
    {
        f_inn >> i;
        for(int j=0;j<i;j++)
        {
            the_planets[j]=generate_planet(f_inn);
            report_planet_properties(*the_planets[i]);
            delete the_planets[j];
        }
        f_inn.close();
    }
    else cout << "Unable to open file";
}
类行星
{
公众:
int id_行星;
浮动x,y,z;
};
无效报告行星属性(行星和P)
{

CUT< P>我不理解代码中的某些部分(例如,为什么你在GeaTypEng行星中创建行星的新实例),但我不是一个有经验的C++程序员。但是,我修改了代码,发现这个代码可以工作:

#include <iostream>
#include <fstream>

using namespace std;

class planet
{
private:
    int id_planet;
    float x,y,z;
public:
    void generate_planet(ifstream& fin);
    void report_planet_properties();
};

void planet::report_planet_properties() {
    cout << "\nPlanet's ID: " << id_planet << endl;
    cout << "\nPlanet's coordinates (x,y,z): ("<< x <<","<< y <<","<< z<<")"<<endl; 
}

void planet::generate_planet(ifstream& fin) {

fin >> id_planet;
fin >> x;
fin >> y;
fin >> z;
} 

int main() {

planet the_planets[10];
int i=0;
ifstream f_inn("route.txt");
if (f_inn.is_open())
{
    f_inn >> i;
    for(int j=0;j<i;j++)
    {
        the_planets[j].generate_planet(f_inn);
        the_planets[j].report_planet_properties();
    }
    f_inn.close();
}
else cout << "Unable to open file\n";
return 0;
}
给出:

Planet's ID: 1

Planet's coordinates (x,y,z): (4,5,6)

Planet's ID: 2

Planet's coordinates (x,y,z): (7,8,9)
如您所见,函数generate_planet()和report_planet_properties()现在是planet类的方法


也许这会对您有所帮助。

如果您为
行星使用正确的索引,那么您的代码将正常工作。

 report_planet_properties(*the_planets[i]);
在上面的行中,您必须使用循环变量
j
not
i
,它是文件中行星的数量

 report_planet_properties(*the_planets[j]);

抱歉…代码行“f_inn>>i”这是因为文件中的第一行显示了我需要创建的类的数量…很好…我理解了你的概念…编辑后得到了正确的输出…非常感谢..^^+1对于面向对象的重构,更进一步的一步是类
>
星球
操作符,呵呵…^^^^^是的…我会保存这两种方法作为将来的参考…再次感谢你们这么多的家伙…天哪…哈哈…我犯了一个粗心的错误…完全有效…谢谢你们…XD我会保存这两种方法…@AmosChew,呵呵,不客气,但你们肯定应该使用PhilipD的方法,因为它是面向对象的,请看我对他的答案的评论!
 report_planet_properties(*the_planets[j]);