Код: Выделить всё
#include
#include
#include
using namespace std;
class child {
public:
child(std::string name,uint32_t age) : name(name),age(age){
}
std::string name;
uint32_t age;
};
class parent {
public:
uint32_t age;
parent(std::string name){
age = 10;
}
std::map child_by_age;
std::map child_by_name;
child& operator[](const uint32_t& num){
return *(child_by_age[num]);
}
child& operator[](const std::string& n){
return *(child_by_name[n]);
}
void addChild(const child& ch){
auto ch_obj = std::make_shared(ch);
child_by_age.emplace(ch.age, ch_obj);
child_by_name.emplace(ch.name, ch_obj);
}
};
class top {
public:
parent p1;
top():p1("p1"){
p1.addChild(child("c0",0));
p1.addChild(child("c1",1));
}
void run(){
p1["c0"].name = "name";
p1[0].name = "name1";
}
};
int main(){
top t;
t.run();
return 0;
}
Код: Выделить всё
operator uint32_t() const{
return age;
}
operator_overload.cpp: В функции-члене 'void top::run()':
operator_overload .cpp:50:11: ошибка: неоднозначная перегрузка для 'operator[]' (типы операндов: 'parent' и 'const char [3]')
p1["c0"].name = "name";
^
operator_overload.cpp:50:11: примечание: кандидат: оператор[](long int, const char*)
operator_overload.cpp:28:12: примечание: кандидат: child& родительский::operator[](const string&)
child& оператор[](const std::string& n){
^~~~~~~~
Я не совсем понимаю, почему компилятор жалуется на оператор индекса, когда я добавляю оператор преобразования
Подробнее здесь: https://stackoverflow.com/questions/793 ... version-op