C++ 输入运算符重载 >>

标签 c++ operator-overloading istream

我有一个名为 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;

最佳答案

正如所怀疑的那样,您通过将对象传递给 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 <<

为避免这种情况,将运算符 << 更改为

friend ostream &operator<<(ostream &out, const BankAccount &bankAccount ) {

这是引用调用,将避免复制 BankAccount 对象

关于C++ 输入运算符重载 >>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20281333/

相关文章:

c++ - C++ dll 中的 Lua 表

c++ - 函数应该返回引用还是对象?

c++ - 从 IStream 读取到缓冲区(音频)

c++ - 如何为递归函数编写方法定义?

c++ 从宏到模板

c++ - mmap 内存区域的总线错误

c++ - 关于重载 "="以及我是否可以避免它

c++ - 如何在 `operator==` 包装类中使用重载 `std::variant` 来比较 Setting Vs Setting 和 T vs T?

c++ - 如何为自定义 istream/streambuf 实现 seekg()?

c++覆盖数组类的>>运算符