2016-01-17 113 views
-5

我有我的类复杂:如何从C++文件创建对象?

#include "Complejo.h" 
#include <sstream> 
Complejo::Complejo() { 
    // TODO Auto-generated constructor stub 
    real = 0; 
    imaginary = 0; 
} 
Complejo::Complejo(int a, int b){ 
    real = a; 
    imaginary = b; 
} 


Complejo::~Complejo() { 
    // TODO Auto-generated destructor stub 
} 
std::string Complejo::mostrar()const{ 
    std::stringstream s; 
    s << real << "+" << imaginary <<"i"; 
    return s.str(); 
} 

在我main我需要读取一个文件(每行有一个复杂的)是这样的:

3 + 5I
4 + 2I
3 + 3i

并创建对象。我怎样才能做到这一点?

+2

您正在寻找[Seraialization](https://en.wikipedia.org/wiki/Serialization)。还要考虑用英文编写代码。我不知道* Complejo *是什么,或者* mostrar *。 – IInspectable

+0

“Complejo”表示“复杂”,“mostrar”表示“显示”@IInspectable – stackptr

回答

0

你可以像下面这样做的每一行:

void Complejo::f(const std::string& line) 
{ 
    std::stringstream s(line); 
    s>>real>>imaginary; 
} 

您可以添加检查一个合法的行等

BTW:在mostrar功能应该能够打印像负值:-1-1i ,因此它可以是:

std::string Complejo::mostrar()const{ 
    std::stringstream s; 
    s << real << (imaginary >= 0) ? "+" : "" << imaginary <<"i"; 
    return s.str(); 
}