2016-01-17 110 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(); 
}