【问题标题】:Error:C2679 binary '==': no operator found which takes a right-hand operand of type 'const std::string' (or there is no acceptable conversion错误:C2679 二进制“==”:未找到采用“const std::string”类型右侧操作数的运算符(或没有可接受的转换
【发布时间】:2018-10-22 10:19:02
【问题描述】:

我已经为将 Employee 类对象存储到向量中的员工管理系统编写了代码,在尝试编译之前我没有收到任何错误,我收到错误:C2679 binary '==': no operator found which采用 'const std::string' 类型的右手操作数(或者没有可接受的转换)。但我不知道为什么任何帮助会很好,谢谢!

// Employee Management System
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Employee
{
public:
    Employee();
    string GetName();
    string GetStatus();
    float GetSalary();
    int GetAge();
    int GetYearHired();

private:
    string m_Name;
    string m_Status;
    float m_Salary;
    int m_Age;
    int m_YearHired;
};

Employee::Employee()
{
    m_Salary = 0;
    m_Age = 0;
    m_YearHired = 0;
}

string Employee::GetName()
{
    string fName;
    string lName;
    cout << "Please enter the new employee's first name: ";
    cin >> fName;
    cout << "Please enter the new employee's last name: ";
    cin >> lName;
    m_Name = fName + lName;
    return m_Name;
}

string Employee::GetStatus()
{
    string status;
    cout
            << "Please enter the employee's status (full time, part time, or manager): ";
    cin >> status;
    return m_Status;
}

float Employee::GetSalary()
{
    float salary;
    cout << "Please enter the employee's salary: ";
    cin >> salary;
    return m_Salary;
}

int Employee::GetAge()
{
    int age;
    while (true)
    {
        cout << "Please enter the employee's age: ";
        cin >> age;
        if (age > 0)
            break;
        else
            cout << "Error: Please enter a positive value.";
    }
    return m_Age;
}

int Employee::GetYearHired()
{
    int yearHired;
    cout << "Please enter what year the employee was hired: ";
    cin >> yearHired;
    return m_YearHired;
}

class Staff
{
    vector<Employee*> emps;
    vector<Employee*>::const_iterator iter;

public:
    Staff();
    virtual ~Staff();
    void Add();
    void Remove();
    void Clear();
    void Display();
};

Staff::Staff()
{
    emps.reserve(20);
}

Staff::~Staff()
{
    Clear();
}

void Staff::Add()
{
    Employee* emp = new Employee;
    emp->GetName();
    emp->GetStatus();
    emp->GetSalary();
    emp->GetAge();
    emp->GetYearHired();
    emps.push_back(emp);
}

void Staff::Remove()
{
    Employee* emp;
    cout << "Which employee would you like to remove?";
    emp->GetName();

    iter = find(emps.begin(), emps.end(), emp->GetName()); // Trying to find the employee in the datbase.
    if (iter != emps.end()) // If the employee is found in the vector it is removed.
    {
        cout << "\n" << *iter << " was removed\n\n";
        emps.erase(iter); // removes employee from the vector.
    }
    else // If the employee is not found in the vector, it tells the user that the employee was not found.
    {
        cout << "Employee not found, please choose anoter employee.\n\n";
    }
}

void Staff::Clear()
{
    cout << "\nDo you really want to clear all employees? (yes/no)\n"; // Asking the user if they want to clear the database.
    string response;
// Storing the response of the user.
    cin >> response; // Getting the users response (yes/no).
    if (response == "yes") // If response is yes.
    {
        vector<Employee*>::iterator iter = emps.begin(); // Declares an iterator for the emps vector and sets it to the beginning of the vector.
        for (iter = emps.begin(); iter != emps.end(); ++iter) // Iterates through vector.
        {
            delete *iter; // Deletes the iterators in the vector, freeing all memory on the heap.* iter = 0;
            // Sets iterator to zero so it does not become a dangling pointer.
        }
        emps.clear(); // Clear vector of pointers.
    }
    else // If response is no.
    {
        cout << "\nAll employee's remain in the database.\n";
    }
}

void Staff::Display()
{
    Employee* emp;
    if (emps.size() == 0) // Checking to see if the database is empty.
        cout
                << "\nThere are no employee's in the database, add employee's to view them here.\n ";
    else // If the cart contains any items.
    {
        cout << "\nThe database contains: \n";
        for (iter = emps.begin(); iter != emps.end(); ++iter) // Displaying the inventory.
        {
            cout << "-------------------------------------------------";
            cout << "Employee's Name         : " << emp->GetName() << endl;
            cout << "Employee's Status       : " << emp->GetStatus() << endl;
            cout << "Employee's Salary       : " << emp->GetSalary() << endl;
            cout << "Employee's Age          : " << emp->GetAge() << endl;
            cout << "Year employee was hired : " << emp->GetYearHired() << endl;
            cout << "-------------------------------------------------";
        }
    }
}

int main()
{
    int option = 0;
    Staff stf;
// Welcoming the user to the Employee Management System program.
    cout
            << "Welcome to our Employee Management System! To get started see the menu options below :\n ";

// Main loop
    while (option != 5) // The loop will repeat until the user enters 5 as the option.
    {
        cout << "------------------------------------------------------------------------------------- - ";
        cout << "\nMenu Options: \n";
        cout << "\nTo select an option, please type in the number that corresponds to that option.\n ";
        cout << "1 - Add an Employee\n2 - Remove an Employee\n3 - Clear the database\n4 - Display Employee's in Database\n5 - Quit" << endl;
        cout << "\nWhat would you like to do? ";
        cout << "------------------------------------------------------------------------------------- - ";

// Start of the validity check.
        bool validInput = false;

        while (!validInput) // The loop will repeat until the users input is valid.
        {
            cin >> option; // User inputs first option choice.
            validInput = true; // Assign the input as valid.
            if (cin.fail()) // Tests to make sure the value assigned is valid for the variable type.
            {
                cout << "\nPlease choose a menu option by number\n";
                cin.clear(); // Clears stream error.
                cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Removes an invalid characters.
                validInput = false; // Sets the input back to false, repeats the loop.
            }
        }

        switch (option)
        {
            case 1:
            {
                stf.Add();
                break;
            }
            case 2:
            {
                stf.Remove();
                break;
            }
            case 3:
            {
                stf.Clear();
                break;
            }
            case 4:
            {
                stf.Display();
                break;
            }
            case 5: // If option = 5.
                cout << "\nThank you for using the Employee Management Program!\n";
                // Thanks the user for using the Employee Management program.
                break;
            default: // If the user does not put in a valid option, it tells them to try again.
                cout << "\nThat's not a valid option. Please try again.\n";
                break;
        }
    }
    system("pause");
    return 0;
}

【问题讨论】:

  • 那么哪一行给出了错误?此外,您不需要大量代码来复制编译器错误。
  • 代码需要一个简单的编辑,其中声明了response,不能自己进行编辑,因为它少于最小字符数。
  • 您需要一个 == 运算符,它可以根据 Employees 的名称比较它们。
  • 顺便说一句,无论你用来格式化这段代码,永远不要再使用它。
  • iter = find(emps.begin(), emps.end(), emp-&gt;GetName()); -- 使用std::find_if,而不是std::find。此外,如果这是问题所在,您可以编写一个重复错误的 3 行 main 程序,而不是发布大量代码。

标签: c++ visual-c++


【解决方案1】:

在我看来(编辑:有一个注释掉)string response; 之前的声明

cin >> response; // Getting the users response (yes/no).

希望这会为您指明正确的方向

编辑: 它在那里,但被注释掉了。试试:

cout << "\nDo you really want to clear all employees? (yes/no)\n"; 
// Asking the user if they want to clear the database.
string response;
// Storing the response of the user.
cin >> response; // Getting the users response (yes/no).
if (response == "yes") // If response is yes.

我会仔细检查所有代码以避免 cmets 干扰代码

【讨论】:

  • 不,他们没有。在那里。无论询问者用来格式化他们的代码的什么格式,都会将其咀嚼并在前几行中用 cmets 打一些代码行。
  • 看上面一行,是布局问题。
  • 如果您使用 CTRL+F,我无法找到早于 cin &gt;&gt; response; 的单词“response”的任何实例,该实例未被注释掉。但是,是的,问题在于评论,我不确定为什么 OP 一开始就没有注意到这一点。也许使用“c++ 中的代码格式化程序”会有所帮助
  • Here 是一个正确格式化代码的链接,可能是 OP 在他们的 IDE 中的方式。我猜想把它贴在这里的人都启用了自动换行。
【解决方案2】:

问题

std::find 会将emps 中的Employee *s 与GetName 返回的std::string 进行比较。没有为 Employee * 定义的比较运算符执行此操作。我们可以做一个,但是因为GetName的行为是为用户获取和命名,而不是简单地返回Employee的名字,这很快就会变得一团糟。

解决方案

首先停止在vectors 中存储指向Employees 的指针。这个简单的改变将消除你过去、现在和未来的绝大部分痛苦。一般来说,尽可能少使用new (Why should C++ programmers minimize use of 'new'?),当你发现自己需要new,prefer a smart pointer。

vector<Employee*> emps;

变成

vector<Employee> emps;

这会在您的代码中产生连锁反应,其中最重要的是

void Staff::Add()
{
    Employee* emp = new Employee;
    emp->GetName();
    emp->GetStatus();
    emp->GetSalary();
    emp->GetAge();
    emp->GetYearHired();
    emps.push_back(emp);
}

必须成为

void Staff::Add()
{
    Employee emp;
    emp.GetName();
    emp.GetStatus();
    emp.GetSalary();
    emp.GetAge();
    emp.GetYearHired();
    emps.push_back(emp);
}

但也要研究emplace_back,并强烈考虑获取用户输入,然后围绕它构建emp。

bool operator==(const Employee & rhs) const
{
    return m_Name == rhs.m_Name;
}

或friend 函数

bool operator==(const Employee & lhs,
                const Employee & rhs)
{
    return lhs.m_Name == rhs.m_Name;
}

然后把调用改成find来比较Employees

iter = find(emps.begin(), emps.end(), emp); // Trying to find the employee in the datbase.

这可能会导致更多问题,因为iter 是一个const_iterator 和一个成员变量(Rubber Ducky wants a word with you about this)。也完全忽略了代码中还有几十个逻辑错误的事实。

【讨论】:

  • @ user4581301 那么我需要让我的const_iterator 只是一个普通的iterator 吗?
  • 编译一下就知道了。
  • @user4581301 如果使用std::find_if 而不是std::find,则无需添加operator ==。
  • 我将emps 向量更改为vector&lt;Employee&gt; emps; 并更改了std::find,但现在我在&lt;&lt; 上收到cout &lt;&lt; "\n" &lt;&lt; iter &lt;&lt; " was removed\n\n"; 的错误,就在"\n" 之后,但是最后一组没有抛出任何错误
  • @user4581301 我得到的错误是没有运算符 "
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多