C++如何从文件动态创建类的多个对象

In C++ how can I create multiple objects of a class from a file dynamically?

本文关键字:对象 创建 动态 文件 C++      更新时间:2023-10-16

我仍然是一个C++新手,一直在努力寻找解决这个问题的任何方法。我有一个格式为多行的文件:

[字符] [双

] [双]

例如:

p 100 0.80
r 50 50
p 20 4.8
r -100 25

我想使用行号的名称将这些行存储在 Complex 类的对象中:

class Complex {
private:
    int name;
    char type;
    double a;
    double b;
public:
    Complex(int name, char type, int x, int y);
    char gettype();
    double geta();
    double getb();
};

我还想使用自定义构造函数创建它们:

Complex::Complex(int name, char type, int x, int y){                    //All data stored in standard form
    if (type = 'p'){
        a = x*cos(y);
        b = x*sin(y);
    }
    else if (type = 'r'){
        a = x;
        b = y;
    }
    else{
        std::cout << "Error" << std::endl;
        a = 0;
        b = 0;
    }
}

我可以将字符串拆分为双精度和字符,但正在努力存储信息。起初我以为我可以使用循环动态命名它们,但我听说不能在C++中动态创建类的实例。然后我考虑创建一个数组,但其他解决方案指出这必须使用默认构造函数来完成?当我不知道会有多少行并使用我自己的构造函数时,有什么方法可以存储这些信息吗?另外,在构造函数中生成的 a 和 b 的值是否会存储在对象中?

处理此问题的最简单方法是将数据存储在 std::vector 中,使用一个构造函数,该构造函数采用字符串 a 将输入行拆分为适当的值,如下所示:

Complex::Complex(int line_no, std::string const& input)
{
   ... Construct complex object using functionality you already know/have ...
}
...
// Process the file
std::ifstream input("inputfile.data");
int line_no = 1;
while (input.is_open() && input.good() && !input.eof())
{
  std::string line;
  std::getline(input, line);
  complex_vector.push_back(Complex(line_no, line));
  ++line_no;
}

就您的构造函数而言,您已经涵盖了ab。还有另外两个成员尚未处理:

Complex::Complex(int name, char type, int x, int y): name(name), type(type){
    // a and b handled here
}

另请注意,'p''r'测试应如下所示:

if (type == 'p'){  // double equals tests for equality