2015-10-21 132 views
-1

赦免在這種情況下的例子,但是:從數組中檢索對象的值?

#include <iostream> 
#include <string> 

using namespace std; 

class A { 
private: 
    string theName; 
    int theAge; 
public: 
    A() : theName(""), theAge(0) { } 
    A(string name, int age) : theName(name), theAge(age) { } 
}; 

class B { 
private: 
    A theArray[1]; 
public: 
    void set(const A value) {theArray[0] = value; } 
    A get() const { return theArray[0]; } 
}; 

int main() 
{ 
    A man("Bob", 25); 
    B manPlace; 
    manPlace.set(man); 
    cout << manPlace.get(); 
    return 0; 
} 

是否有可能對我來說,當我打電話檢索主的「人」對象的內容manPlace.get()?我打算在打電話給manPlace.get()時打印姓名(Bob)和年齡(25歲)。我想將一個對象存儲在另一個類中的一個數組中,我可以在main中檢索所述數組的內容。

+0

'const A&temp = manPla ce.get();'? –

回答

0

您需要在您的A類上定義ostream::operator<<來完成此操作,否則應該生成的文本輸出的年齡和名稱格式未定義(並且它們是A類的私有成員)。

查看參考ostream::operator<<。爲了您的一類,這樣的操作可以這樣定義:

std::ostream& operator<< (std::ostream &out, A &a) { 
    out << "Name: " << a.theName << std::endl; 
    out << "Age: " << a.theAge << std::endl; 
    return out; 
} 

這將輸出類似:

Name: XX 
Age: YY 

所以,你的完整代碼如下:

#include <iostream> 
#include <string> 

using namespace std; 

class A { 
private: 
    string theName; 
    int theAge; 
public: 
    A() : theName(""), theAge(0) { } 
    A(string name, int age) : theName(name), theAge(age) { } 
    friend std::ostream& operator<< (std::ostream &out, A &a) { 
    out << "Name: " << a.theName << std::endl; 
    out << "Age: " << a.theAge << std::endl; 
    return out; 
    } 
}; 

class B { 
private: 
    A theArray[1]; 
public: 
    void set(const A value) { theArray[0] = value; } 
    A get() const { return theArray[0]; } 
}; 

int main() 
{ 
    A man("Bob", 25); 
    B manPlace; 
    manPlace.set(man); 
    cout << manPlace.get(); 
    return 0; 
} 

這將輸出:

Name: Bob 
Age: 25 
+0

謝謝你,我感謝你的幫助。 – dc90