【问题标题】:C++ Operator ">>" overloading errorC++ 运算符“>>”重载错误
【发布时间】:2015-07-04 21:48:42
【问题描述】:

我需要重载operator >> 来帮助我从文件中读取我的配置。这就是我想出的:

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

使用如下:

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

我在同一件事上遇到多个错误:

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

我很乐意为您提供任何帮助。谢谢。

【问题讨论】:

  • file1和file2打开同一个文件可以吗?

标签: c++ file templates operator-overloading istream


【解决方案1】:

您传递给提取运算符的参数不正确:

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

如果是const,您不能很好地将流中的值提取到w!将其更改为通过 non-const 引用您的 config&lt;T&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多