aUs*_*elf 1 c++ operator-overloading istream
我有一个名为的基本类BankAccount,如下所示:
class BankAccount {
private:
char* accountId;
int* ownerId;
double* accountBalance;
// some other methods here...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是关于使用输入运算符创建对象。我观察到,当我使用它时,实际上创建了 2 个对象,因为析构函数最终被调用了两次:
1. The implicit constructor is called
2. The values for initializing the object are provided from the stdin
3. The copy constructor is called
4. The destructor is called twice
5. The object is printed to the stdout
Run Code Online (Sandbox Code Playgroud)
你能解释一下它是如何工作的吗?它是否可以避免?我想参数bankAccount是直接修改的。
我的职能是:
// 3. input operator
friend istream &operator>>(istream &in, BankAccount &bankAccount ) {
cout << "Enter the account ID:" << endl;
in.get(bankAccount.accountId, SIZE);
cout << "Enter the owner ID:" << endl;
in >> *bankAccount.ownerId;
cout << "Enter the account balance:" << endl;
in >> *bankAccount.accountBalance;
return in;
}
// 4. output operator
friend ostream &operator<<(ostream &out, BankAccount bankAccount ) {
out << endl;
out << "Account id: " << bankAccount.getAccountId();
out << endl;
out << "Owner id: " << bankAccount.getOwnerId();
out << endl;
out << "Account balance: " << bankAccount.getAccountBalance();
out << endl << endl;
return out;
}
Run Code Online (Sandbox Code Playgroud)
和调用:
BankAccount bankAccount;
cout << "Enter the values to build a new object: " << endl;
cin >> bankAccount;
cout << bankAccount;
Run Code Online (Sandbox Code Playgroud)
怀疑您通过将对象传递给按值调用来获取副本operator <<
BankAccount bankAccount; // Default constructor call
cout << "Enter the values to build a new object: " << endl;
cin >> bankAccount; // Read in values
cout << bankAccount; // Create a copy of bankAccount and pass it to operator <<
Run Code Online (Sandbox Code Playgroud)
为了避免这种变化,运算符 << 到
friend ostream &operator<<(ostream &out, const BankAccount &bankAccount ) {
Run Code Online (Sandbox Code Playgroud)
这是按引用调用,将避免复制 BankAccount 对象