模板化操作符创建一个错误,指出操作符是二义性的

Templated operator creates an error stating that the operator is ambiguous

本文关键字:操作符 错误 二义性 一个 创建      更新时间:2023-10-16

我定义了一个模板化的操作符,以满足操作符形参中的两种类型的输入。在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

<标题>包括"BankAccount.h"h1> 是也在这个函数中提供了错误(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 "Cashpoint.h"(contains #includes "BankAccount.h")

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;
}

编辑:操作符>>可能与Cashpoint.h中包含BankAccount.h有关

您超载operator>>的方法在我看来很奇怪。

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

你基本上是在说:不管T是什么类型,在它上面调用getDataFromStream方法。这没有任何意义!它也将给出一个模糊的过载,因为编译器现在有两个operator>>可能调用当Tstd::string:一个从你的代码和一个从标准库。

看起来你只是想为BankAccount类型添加一个重载。

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