【发布时间】:2016-07-04 00:38:55
【问题描述】:
我有一个名为形状的基类,它具有 3D 形状的派生类,即 Ball 或 Tetraeder。 我的程序应该从文本文件中读取形状的类型及其参数,并将体积和面积写入输出文本。
#include <fstream>
#include <string>
#include <sstream>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include "Shape.h"
#include "Ball.h"
#include <vector>
using namespace std;
int
main( int argc, char** argv )
{
string input = string(argv[1]);
string output = string(argv[2]);
ifstream file(input);
string line;
string shapename;
int nx = atoi(argv[3]);
int ny = atoi(argv[4]);
int nz = atoi(argv[5]);
while (std::getline(file, line))
{
std::stringstream lineStream(line);
lineStream >> shapename;
int value;
std::vector<int> lineData;
while (lineStream >> value)
{
lineData.push_back(value);
}
Shape * objShape = new shapename(lineData);
objShape -> calc_volume;
objShape -> calc_projection(nx,ny,nz);
std::ofstream f(output);
f << objShape -> get_volume() << " " << objShape -> get_projection << endl;
}
}
我现在的问题是如何从文本文件中的字符串创建对象,尤其是在不知道所有派生类的情况下。
应该可以在不更改代码的情况下向程序中添加更多形状,只需添加新文件即可。
【问题讨论】:
-
谷歌工厂模式。
标签: c++ inheritance