使用重载的 >> 运算符调用 CPP 构造函数

Calling CPP Constructor with overloaded >> operator

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

?

使用重载的 >> 运算符根据用户输入创建对象的正确方法是什么?您会怎么做? 如果我想这样做,我将不得不写

Client* client;
cin >> client;

但此时客户端已经创建...

谢谢

你可以这样做(客户端指针需要通过引用传递,然后读取到临时变量并创建客户端):

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