I have class of worker, each worker has an array of pointers to co workers that are also workers.
I want to overload = operator so I will be able to do the following: *worker1 = *worker2.
This opertion will add worker2 to array of coworkers of worker1, and worker1 to array of coworkers of worker2. (worker1, worker2 are pointers).
Relevant Worker class structure:
class Worker{
private:
Worker** coWorkers
}
The function that I have tried to implement:
const Worker& Worker::operator =(const Worker& other){
}
The problem is the "other" is const but "coWorkers" is not const so I can't do the following:
this->coWorkers[last] = &other;
How I can solve this problem?
CodePudding user response:
First of all modern C way to do so use std::vector or std::list instead of Worker** coWorkers
.
I think in your case list is preferred because you don't know the exact number of coworkers during initialization, as well as container i.e. list of co-workers can be changed in time i.e. new coworkers added and someone rotated, switch company etc.
You can push back a worker to the list as shown in example bellow:
#include <list>
#include <string>
#include <iostream>
class Worker {
public:
typedef std::list< Worker >::const_iterator const_iterator;
explicit Worker(const std::string& name):
name_(name)
{}
Worker& operator =(const Worker& coWorker)
{
coWorkers_.push_back(coWorker);
return *this;
}
const_iterator begin() const {
return coWorkers_.cbegin();
}
const_iterator end() const {
return coWorkers_.cend();
}
const std::string& name() const {
return name_;
}
private:
std::string name_;
std::list< Worker > coWorkers_;
};
int main(int argc, const char** argv)
{
Worker boss("Cesar");
boss = Worker("Augustus");
boss = Worker("Antonius");
boss = Worker("Brutus");
std::cout << boss.name() << std::endl;
for(auto i: boss) {
std::cout << i.name() << std::endl;
}
}
Check output