C++ C++;输入运算符重载>&燃气轮机;

C++ C++;输入运算符重载>&燃气轮机;,c++,operator-overloading,istream,C++,Operator Overloading,Istream,我有一个名为BankAccount的基本类,如下所示: class BankAccount { private: char* accountId; int* ownerId; double* accountBalance; // some other methods here... } 我的问题是关于使用输入操作符创建对象的。我观察到,当我使用它时,实际上创建了两个对象,因为析构函数最后被调用了两次: 1. The implici

我有一个名为BankAccount的基本类,如下所示:

class BankAccount {
    private:
        char* accountId;
        int* ownerId;
        double* accountBalance;
    // some other methods here...
}
我的问题是关于使用输入操作符创建对象的。我观察到,当我使用它时,实际上创建了两个对象,因为析构函数最后被调用了两次:

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;
}
//3。输入运算符
朋友istream和运营商>>(istream和in、银行账户和银行账户){

cout根据怀疑,您通过将对象传递给
操作符来获得副本。根据怀疑,您通过将对象传递给
操作符来获得副本。您编写的函数中根本没有创建任何对象(因为您所做的一切都使用引用)。您观察到的行为必须发生在程序的其他地方。您的假设(直接修改银行账户)是正确的。如果看不到您实际调用此运算符的位置,则无法回答此问题。您是否也可以显示Ah。开始了。
BankAccount;BankAccount;
是默认构造。您提到的直接输入是正确的,我们还必须查看输出运算符的实现,但除非它引用rence(const或not),这是您的复制构造点。由于存在两个对象(初始对象和副本),您将得到两个销毁。这样,正如怀疑的那样,输出运算符param是一个值copy,因此存在您的复制运算符。
friend-ostream&operator在您编写的函数中根本没有创建任何对象(因为你所做的一切都使用引用)。你观察到的行为一定发生在你程序的其他地方。你的假设(银行账户直接被修改)是正确的。如果看不到您实际调用此运算符的位置,则无法回答此问题。您是否也可以显示Ah。开始了。
BankAccount;BankAccount;
是默认构造。您提到的直接输入是正确的,我们还必须查看输出运算符的实现,但除非它引用rence(const或not),这是您的复制构造点。由于存在两个对象(初始对象和副本),您将得到两个销毁。这样,正如所怀疑的那样,输出运算符参数是一个值copy,因此存在您的复制运算符。
friend ostream&operator
BankAccount bankAccount;
cout << "Enter the values to build a new object: " << endl;
cin >> bankAccount;
cout << bankAccount;
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 ) {