2015-12-17 24 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'。 –