使用重载>>调用CPP构造函数操作者

时间:2015-12-17 15:56:58

标签: c++ constructor operator-overloading

我对c ++很新,我想知道以下是否可行:

考虑你有

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;
}

使用重载的&gt;&gt;基于用户输入创建对象的正确方法是什么?操作员,你会怎么做? 如果我想这样做,我将不得不写

Client* client;
cin >> client;

但是那时,客户端已经创建了......

感谢

1 个答案:

答案 0 :(得分: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