运算符重载和通道

时间:2014-07-15 07:51:45

标签: c++ overloading operator-keyword chaining

有人可以帮助我回答这些问题吗?我很难理解运算符重载和链接。

  1. 如何在程序中为操作员+功能执行链接?
  2. 为什么操作员不能"<<&#;作为成员函数重载?
  3. 参考operator +函数,它返回的Bank_Acct对象的名称是什么?

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    const int SIZE = 10;
    
    class Bank_Acct
    {
    public:
        Bank_Acct( );  // default constructor
        Bank_Acct(double new_balance, string Cname); // explicit value                                          
                                             // constructor
        void Print( ); //accessor function
        Bank_Acct & operator+(double amount); // mutator function
    
    private:
        double balance;
        string name;
    };
    
    Bank_Acct::Bank_Acct()
    {
        balance = 0;
        name = "NoName";
    }
    
    Bank_Acct::Bank_Acct(double amount, string Cname)
    {
        balance = amount;
        name = Cname;
    
    }
    
    void Bank_Acct::Print()
    {
        cout << endl << "Object name: " << name;
        cout << endl << "The new balance is: " << balance << endl;
    }
    
    Bank_Acct & Bank_Acct::operator+(double amount)
    {
        balance += amount;
        return *this;
    }
    
    int main()
    

    {         Bank_Acct my_Acct;

        cout.setf(ios::showpoint);
        cout.setf(ios::fixed);
        cout.precision(2);
    
        cout << "Original balance of my_Acct:" << endl;
        cout << "----------------------------" << endl;
        my_Acct.Print( );
    
        // the following statement contains chaining
        my_Acct + 18.75 + 14.35 + 10054.96;
    
        cout << endl << endl;
    
        cout << "The balance of my_Acct after addition to balance 3 times:" << endl;
        cout << "---------------------------------------------------------" << endl;
        my_Acct.Print();
    
        cout << endl << endl;
    
        return 0;
    }
    

1 个答案:

答案 0 :(得分:0)

  1. 它返回修改对象的引用,因此您可以再次调用operator +。
  2. 你绝对可以重载&lt;&lt;作为成员函数,但如果您打算将其用作流操作符,则不会,因为左侧将是ostream而不是Bank_Acct
  3. 是指向已调用成员函数的类实例的指针。