Já mám robota, který má za ukazatel vektor ints (obchod, práce, historie), nicméně když jsem kopírování objektu z jednoho robota na druhého, a první robot dostane mimo rozsah, a pak jsem vytisknout historii robot to mi dává masivní seznam náhodných čísel. Já jsem se snažil dělat své vlastní kopie konstruktoru a nastavení _history na nové objekty _history hodnotu o hodnotu, ale dává stejnou odpověď.
ROBOT.h
# pragma once
#include <iostream>
#include <vector>
class Robot{
private:
int workUnit = 0;
std::vector<int>* _history; // pointer to vector of ints (NOT a vector of int pointers)
public:
Robot() : name("DEFAULT") {_history = new std::vector<int>();};
Robot(const std::string& name) : name(name){_history = new std::vector<int>();};
~Robot(){std::cout << name << ": Goodbye!" << std::endl; delete _history;};
std::string whoAmI() const {return name;};
void setName(const std::string& name){this->name = name;};
void work();
void printWork() const;
std::vector<int>* getHistory() const { return _history; };
protected:
std::string name;
};
ROBOT.cpp
# include "Robot.h"
void Robot::work(){
workUnit++;
_history -> push_back(workUnit);
std::cout << name << " is working. > " << workUnit <<"\n";
}
void Robot::printWork() const {
std::cout << "Robot " << name << " has done the following work: ";
for(const int& record : *_history){
std::cout << record << " ";
}
std::cout << std::endl;
}
HLAVNÍ
#include <iostream>
#include "Robot.h"
int main(){
Robot r2("Task5 Robo");
{
Robot r1("r1");
r1.whoAmI();
r1.work();
r1.work();
r1.printWork();
std::cout << "assign r1 to r2..." << std::endl;
r2 = r1;
r2.setName("r2");
r2.whoAmI();
r2.printWork();
}
r2.whoAmI();
r2.printWork();
std::cout << "end of example code..." << std::endl;
return 0;
}
VÝSTUP iam dostat :
r1 is working. > 1
r1 is working. > 2
Robot r1 has done the following work: 1 2
assign r1 to r2...
Robot r2 has done the following work: 1 2
r1: Goodbye!
Robot r2 has done the following work: 7087248 0 6975376 0 0 0 -1124073283 19523 7087248 0 6975408 0 7087248 0 6947152 0 0 -1 -1174404934 19523 7087248 0 6947152 0 1701603654 1917803635 1701602145 1986087516 1634360417 (and lots more random numbers)