2015-12-17 28 views
0

我很新的C++,我想知道,如果以下是可能的:調用CPP構造與重載>>運算

考慮你有

class Client { 
public: 
    Client(string firstname, string lastname); 
// ... 
} 

你可以重載>>運營商用剛剛輸入的輸入生成一個新對象?

istream& operator>> (istream& is, Client* client) { 
    cout << "First Name: "; 
    is >> client->firstName; 
    cout << "Last Name: "; 
    is >> client->lastName; 
    return is; 
} 

什麼是正確的方式來創建一個基於用戶輸入使用重載>>運算符的對象,你會怎麼做? 如果我想這樣做,這樣,我會寫

Client* client; 
cin >> client; 

但在那一刻,客戶端已創建...

感謝

+0

你的例子沒有意義。雖然你可以寫一個能夠回報你價值的經營者,但你失去了鏈接能力;在這一點上最好只寫'istream&'構造函數 –

+1

爲什麼它沒有意義? – user3787706

+0

因爲它也需要指向對象的指針,所以IOW不能解決您的問題。 –

回答

2

你可以像下面這樣做(需要通過引用傳遞客戶端的指針,然後讀取到臨時變量並創建客戶端):

istream& operator >> (istream& is, Client * &client) { 
    string firstname, lastname; 
    cout << "First Name: "; 
    is >> firstname; 
    cout << "Last Name: "; 
    is >> lastname; 
    client = new Client(firstname, lastname); 
    return is; 
} 

Client* client; 
cin >> client; 
// use client 
delete client; 

但我不會建議一般。更清潔的方式是有

istream& operator >> (istream& is, Client &client) { 
    cout << "First Name: "; 
    is >> client.firstname; 
    cout << "Last Name: "; 
    is >> client.lastname; 
    return is; 
} 

Client client; 
cin >> client; 
// use client 
// client destroyed on scope exit 
+1

是或者客戶端客戶端(std :: cin)'。或'客戶端客戶端(Client :: constructFromInputStream(std :: cin))'。 –

+0

第一個沒有客戶端客戶端工作嗎? 那麼:怎麼樣? 'cin >>客戶端;'它會在運營商內部創建? – user3787706

+0

@ user3787706:是的。但是你需要一個'Client * client_ptr'。 –