2011-06-03 36 views
-1

我想做一些不尋常的事情。我有一個類模板:製作模板類獲得另一個類<T>並將其視爲數據類型(C++)

template<class T> class CFile 

我想打造的又一類將是int型的一員,

class foo 
{ 
private: 
    int memb; 
} 

當我通過「富」類爲「< T>」,以「CFile」,foo應該簡單地作爲整數。我需要在foo中使用foo的內部邏輯來實現它的想法CFile(CFile不允許包含任何從類中提取int成員的邏輯)。

這是一個大學的任務,所以我不應該改變給我的規則。它應該看起來像這樣:

class foo 
{ 
    int memb; 
} 

int main() 
{ 
    foo myFoo; 

    // The ctor of CFile takes a file path and opens the file. After that it can write 
    // members from type <T> to the file. I need the CFile to write the memb member to 
    // the file (Remember that the CFile is passed as <T> 

    CFile<foo> file("c:\\file.txt"); 

} 

謝謝。

+6

你能澄清你問什麼?我不確定我是否理解你的意思,「把整個班級當作」memb「int成員。」 – templatetypedef 2011-06-03 20:33:57

+1

您應該說明您正在嘗試解決的問題,而不是您使用方法找到的問題。如果相關,包括什麼是'CFile',以及爲什麼你不能修改它。 – 2011-06-03 20:36:52

+2

我不確定我瞭解你的問題。你想把'operator const int(){return memb;}'加到'foo'嗎? – a1ex07 2011-06-03 20:40:05

回答

1

我認爲你想要做的是使class foo作爲一個整數。爲此,您需要提供:

  • 一個構造函數,可以從int創建foo
  • 一個重載的鑄造操作符,它會將foo類隱式轉換爲int

您將有這樣的事情:

class foo { 
public: 
    foo() {} // Create a foo without initializing it 
    foo(const int &memb): _memb(memb) {} // Create and initialize a foo 

    operator int&() {return _memb;} // If foo is not constant 
    operator const int&() const {return _memb;} // If foo is constant 

private: 
    int _memb; 
}; 
+0

是的,這就是我的意思。謝謝! – max12345 2011-06-03 21:33:20

0

如果CFile的使用流寫入到文件,那麼你只需要實現運營商< <在Foo類。

喜歡的東西:

ofstream file; 

file.open("file.txt"); //open a file 

file<<T; //write to it 

file.close(); //close it 

在CFile的,這加入到富:

ofstream &operator<<(ofstream &stream, Foo& foo) 
{ 
    stream << foo.memb; 

    return stream; 
} 
相關問題