我有一个名为BankAccount
的基本类,如下所示:
class BankAccount {
private:
char* accountId;
int* ownerId;
double* accountBalance;
// some other methods here...
}
我的问题是使用输入操作符创建对象。我观察到,当我使用它时,实际上创建了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
你能解释一下它是如何实际运作的,是否可以避免?我认为参数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;
}
和调用:
BankAccount bankAccount;
cout << "Enter the values to build a new object: " << endl;
cin >> bankAccount;
cout << bankAccount;
答案 0 :(得分:4)
怀疑是通过将对象传递给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 <<
为了避免这种改变运算符&lt;&lt;到
friend ostream &operator<<(ostream &out, const BankAccount &bankAccount ) {
这是按引用调用并且将避免复制BankAccount对象