模板化运算符会创建一个错误,指出操作符不明确

时间:2014-05-11 16:18:21

标签: c++ templates operator-overloading

我已经定义了一个模板化运算符,以满足运算符参数中的两种输入类型。 getDataFromStream()出现错误,如何定义运算符以消除这种歧义?

BankAccount.h

template <typename T>
istream& operator>>( istream&, T&);     //input operator

template <typename T>
istream& operator>>( istream& is, T& aBankAccount) {
//get BankAccount details from stream
    return ( aBankAccount.getDataFromStream( is));
}

BankAccount.cpp

包括&#34; BankAccount.h&#34;

void BankAccount::readInBankAccountFromFile( const string& fileName) {
    ifstream fromFile;
    fromFile.open( fileName.c_str(), ios::in);  //open file in read mode
    if ( fromFile.fail())
        cout << "\nAN ERROR HAS OCCURED WHEN OPENING THE FILE.";
    else
        fromFile >> (*this);    //read  all info from bank account file
                 ^^
    fromFile.close();           //close file: optional here
}

但也是在这个提供错误的功能中 (BankAccount.cpp)

istream& BankAccount::getDataFromStream( istream& is) {
//get BankAccount details from stream
    is >> accountType_;                     //get account type
    is >> accountNumber_;                   //get account number
    is >> sortCode_;                        //get sort code
    is >> creationDate_;                    //get creation date
    is >> balance_;                         //get balance_
    is >> transactions_;                    //get all transactions (if any)
    return is;
}

Cashpoint.cpp #includes&#34; Cashpoint.h&#34;(包含#includes&#34; BankAccount.h&#34;)

bool CashPoint::linkedCard( string cashCardFileName) const {
//check that card is linked with account data
    ifstream inFile;
    inFile.open( cashCardFileName.c_str(), ios::in);    //open file
    bool linked(false);
    if ( ! inFile.fail()) //file should exist at this point 
    {   //check that it contain some info in addition to card number
        string temp;
        inFile >> temp; //read card number
        inFile >> temp; //ready first account data or eof
        if (inFile.eof())
            linked = false;
        else
            linked = true;
        inFile.close();         //close file: optional here
    }
    return linked;
}

编辑:运营商&gt;&gt;上的cashpoint.cpp和bankaccount.cpp中的错误 可能与在Cashpoint.h中包含BankAccount.h有关。

1 个答案:

答案 0 :(得分:0)

你的重载方法operator>>对我来说似乎很奇怪。

template <typename T>
istream& operator>>( istream& is, T& aBankAccount) {
//get BankAccount details from stream
    return ( aBankAccount.getDataFromStream( is));
}

您基本上是这样说的:无论T是什么类型,都可以在其上调用方法getDataFromStream。这没有任何意义!它也会产生模糊的重载,因为当operator>>T时,编译器现在有两个std::string可能会调用:一个来自您的代码,另一个来自标准库。

看起来您只想为BankAccount类型添加重载。

istream& operator>>(istream& is, BankAccount& aBankAccount) {
    return ( aBankAccount.getDataFromStream( is));
}