新的新类对象的函数;错误:非静态成员引用必须相对于特定对象

The function of a new new class object; error: A nonstatic member reference must be relative to a specific object

本文关键字:对象 引用 静态成员 相对于 函数 新类 错误      更新时间:2023-10-16

我想创建一个雇用(创建一个新的类对象)新员工的函数。我决定使用默认构造函数(如果不是好决定,请纠正我)。我有错误Employee::Hire(employees);

#include <iostream>
#include <string>
#include <vector>
class Employee
{
private:
    std::string name;
public:
    Employee::Employee()
    {
        std::cout << "test" << std::endl;
    }
    void Employ(std::vector<Employee> &v)
    {
        v.push_back(Employee());
    }
};
int main()
{
    std::vector<Employee> employees;
    Employee::Employ(employees);
    system("pause");
}

如何解决?

此函数:

void Employ(std::vector<Employee> &v)
{
    v.push_back(Employee());
}

应该移出Employee的类定义。 成员函数对类的实例进行操作,但您打算在没有任何实例的情况下调用它。

或者,该功能可以static,但是恕我直言,首选样式是仅使用非成员。