【问题标题】:Program has errors, binary operators程序有错误,二元运算符
【发布时间】:2018-04-21 02:50:11
【问题描述】:
#include <iostream>
#include <fstream>
using namespace std;
class InsurancePolicy
{
    friend fstream&  operator<<(fstream&, InsurancePolicy);
    friend istream& operator>>(istream&, InsurancePolicy&);
private:
    int policyNum;
    string lastName;
    int value;
    int premium;
};
fstream& operator<<(fstream& out, const InsurancePolicy pol)
{
    out << pol.policyNum << " " << pol.lastName << " " << pol.value << " " << pol.premium << endl;
    return out;
}
istream& operator>>(istream& in, InsurancePolicy& pol)
{
    in >> pol.policyNum >> pol.lastName >> pol.value >> pol.premium;
    return in;
}
int main() {
    ofstream outFile;
    outFile.open("Policy.txt");
    InsurancePolicy aPolicy[10];
    for (int count = 0; count < 10; ++count)
    {   
        printf("Enter the policy number, the holder's last name, the value, and the premium.");
        cin >> aPolicy[count];
        outFile << aPolicy[count] << endl;
    }
    return 0;

}

由于以下错误,该程序将无法编译: 严重性 代码 描述 项目 文件 线 抑制状态 错误 C2679 二进制“>>”:未找到采用“std::string”类型右侧操作数的运算符(或没有可接受的转换) 项目6 c:\users\preston freeman\source\repos\jave.cpp 21

错误 C2679 二进制“

错误 C2679 二进制“

如何解决这些错误? 感谢您的宝贵时间。

【问题讨论】:

  • 常规重载在ostream,而不是fstream。并再次检查您的函数原型。

标签: c++


【解决方案1】:

你正在使用

ofstream outFile;

主要。 但是您的运算符重载是

 friend fstream&  operator<<(fstream&, InsurancePolicy);

请注意ofstream 不是从fstream 派生的,这就是为什么为fstream 重载operator &lt;&lt; 不会使其对ofstream 起作用

您可以简单地将fstream 更改为ofstream

ofstream& operator<<(ofstream& out, const InsurancePolicy pol)
{
    out << pol.policyNum << " " << pol.lastName << " " << pol.value << " " << pol.premium << endl;
    return out;
}

最好通过 const& 传入 InsurancePolicy,因为 ofstream 不会更改它,并且复制用户定义的对象可能很昂贵

ofstream& operator<<(ofstream& out, const InsurancePolicy& pol)

您可能还需要#include &lt;string&gt;

演示: https://ideone.com/rJiw21

【讨论】:

  • 看起来你正在使用visual studio,所以你可能还需要#include
  • 文件行抑制状态错误 LNK2019 无法解析的外部符号 "class std::basic_ofstream> & __cdecl operator > &,class InsurancePolicy &)" (??6@YAAAV?$basic_ofstream@DU?$char_traits@D@std@@@std@@AAV01@AAVInsurancePolicy@@@Z) 在函数中引用_main Project6 c:\Users\preston freeman\source\repos\Project6\Project6\jave.obj 1 Error LNK1120 1 unresolved externals Project6 c:\Users\preston freeman\source\repos\Project6\Debug\Project6.exe 1跨度>
  • 查看这个演示,ideone.com/rJiw21,它编译得很好。您确定函数的声明和定义具有完全相同的签名吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
相关资源
最近更新 更多