C++如何从文件动态创建类的多个对象
In C++ how can I create multiple objects of a class from a file dynamically?
我仍然是一个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;
}
就您的构造函数而言,您已经涵盖了a
和b
。还有另外两个成员尚未处理:
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
相关文章:
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 具有包含其他对象的类的对象创建顺序
- 为什么我们再次从结构对象创建结构变量?
- 将对象创建为全局/静态对象会崩溃,而本地对象不会崩溃
- 如何创建一个对象创建函数,该函数将由与其关联的名称调用?
- 如何为自定义模板对象创建专门的函数模板
- 对象创建错误的C++矢量
- 如何为Python Swigged C++对象创建和分配回调函数
- 在 C++ 中为 C 样式对象创建一个透明包装类
- 此类模板的对象创建如何工作?
- C++ 中的对象创建类型有什么区别?
- 未知大小的数组作为类成员,用于在运行时(对象创建时间)创建数组的对象
- 如何仅通过父类对象限制对象创建
- 在正确性或良好的代码结构方面,这种动态对象创建看起来如何
- 无法将类对象创建为另一个类的成员
- 如何从现有基类对象创建派生类对象
- 在 DTor 之前删除的静态对象创建的线程?
- C++:定义多个构造函数时的对象创建/销毁序列
- 从对象创建矢量包装器,该对象只允许使用索引访问向量
- 是否可以为CPP中的对象创建一组指针