简体   繁体   中英

C++ Operator “>>” overloading error

I need to overload operator >> to help me read my configuration from a file. This is what i came up with:

template<typename T>istream& operator>>(istream &in, const config<T> &w) 
{
    in>>w.attribName1;
    for(int z=0;z<3;z++)
    {   
        in>>w.attribute1[z];
    }

    in>>w.attribName2;
    for(int x=0;x<3;x++)
    {
        in>>w.attribute2[x];
    }


    in>>w.attribName3;
    for(int v=0;v<3;v++)
    {   
        in>>w.attribute3[v];
    }


    in>>w.attribName4;
    for(int n=0;n<3;n++)
    {   
        in>>w.attribute4[n];
    }

    return in;
}

Which is used like:

int _tmain(int argc, _TCHAR* argv[])
{   
    double val2[3]={4.124,7.07,12.01};
    string FILE1NAME,FILE2NAME,file1name1,file1name2,file1name3,file1name4;
    FILE1NAME="Config_file_no1";
    FILE2NAME="cfg2";
    file1name1="Volume";
    file1name2="Screen_mode";
    file1name3="Color_settings";
    file1name4="Sensitivity";
    ofstream file1(FILE1NAME+".ini");
    ifstream file2(FILE1NAME+".ini");

    config<double> first;
    config<double> second;
    first.setAttribName1(file1name1);
    first.setAtt1(val2);
    first.setAttribName2(file1name2);
    first.setAtt2(val2);
    first.setAttribName3(file1name3);
    first.setAtt3(val2);
    first.setAttribName4(file1name4);
    first.setAtt4(val2);

    file2 >> second;

    system("pause");
    return 0;
}

I get multiple errors with the same thing :

Error   1   error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)  d:\(path)   193 1   projekt_v2

I will be glad for any assistance. Thank you.

The arguments you pass to your extraction operator are incorrect:

template<typename T>
istream& operator>>(istream &in, const config<T> &w) 

You can't very well extract the values from the stream into w if it's const ! Change that to take your config<T> by non - const reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM