I'm trying to use a vector for derived class Employee
but I got en error:
class Company : public Employee, public TesterEmployee, public DeveloperEmployee {
private:
std::vector<Employee*> _table;
public:
friend std::vector<Employee*>& operator+=(const Employee* emp) {
_table.push_back(emp->clone());
return *this;
}
};
The error is:
error:
'std::vector<Employee*>& operator+=(const Employee*)'
must have an argument of class or enumerated type
+=
is a binary operator. The function
friend std::vector<Employee*>& operator+=(const Employee* emp) {
_table.push_back(emp->clone());
return *this;
}
defines a non-member function that can take only one argument. Hence, it cannot be used in an expression like:
a += b;
What you need is:
Company& operator+=(const Employee* emp) {
_table.push_back(emp->clone());
return *this;
}
In response to the other question about the same code (that you deleted https://stackoverflow.com/questions/30717107/operator-overloading-in-my-class-with-error ):
Q and the problem :
error: invalid operands of types 'Company*' and 'DeveloperEmployee*' to binary 'operator+'|
What does it mean?
It means you're trying to write Java/C# code in C++. Don't do that.
In particular you're abusing OOP for the sake of OOP. A Company
is-not-a Employee
(see Liskov ), and company + employee
doesn't make sense.
Lose the new
.
Lose the base class.
Probably lose the clone
based dynamic value semantics.
Finally, your problem is, you're using operator+=
which you didn't overload.
#include <vector>
#include <iostream>
struct Employee {
int getID() const { return _id; }
private:
int _id = generate_id();
static int generate_id() {
static int next = 0;
return ++next;
}
};
struct DeveloperEmployee : Employee {
DeveloperEmployee(std::string const& descr, std::string const& project)
: _description(descr), _project(project) { }
private:
std::string _description;
std::string _project;
friend std::ostream& operator<<(std::ostream& os, DeveloperEmployee const& de) {
return os << "id:" << de.getID() << " descr:'" << de._description << "' project:'" << de._project << "'";
}
};
class Company {
private:
std::vector<Employee> _table;
std::string _des;
public:
Company &operator+=(const Employee &emp) {
_table.push_back(emp);
return *this;
}
void setDescription(std::string des) { _des = des; }
};
int main() {
Company company;
DeveloperEmployee a("description", "project");
int id = a.getID();
std::cout << a << std::endl; // Developer ID = 2, project = hw5
company += a;
}
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.