Код: Выделить всё
#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);
}
operator uint32_t() const{
return age;
}
};
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_overload.cpp: In member function ‘void top::run()’:
operator_overload.cpp:50:11: error: ambiguous overload for ‘operator[]’ (operand types are ‘parent’ and ‘const char [3]’)
p1["c0"].name = "name";
^
operator_overload.cpp:50:11: note: candidate: operator[](long int, const char*)
operator_overload.cpp:28:12: note: candidate: child& parent::operator[](const string&)
child& operator[](const std::string& n){
^~~~~~~~
Код: Выделить всё
child& operator[](const char* n){
return (*this)[std::string(n)];
}
Код: Выделить всё
p1[0].name = "name1";
operator_overload.cpp: In member function ‘void top::run()’:
operator_overload.cpp:55:11: error: ambiguous overload for ‘operator[]’ (operand types are ‘parent’ and ‘int’)
p1[0].name = "name1";
^
operator_overload.cpp:25:12: note: candidate: child& parent::operator[](const uint32_t&)
child& operator[](const uint32_t& num){
^~~~~~~~
operator_overload.cpp:29:12: note: candidate: child& parent::operator[](const string&)
child& operator[](const std::string& n){
^~~~~~~~
operator_overload.cpp:33:12: note: candidate: child& parent::operator[](const char*)
child& operator[](const char* n){
Где определена следующая встроенная перегрузка
Код: Выделить всё
operator_overload.cpp:50:11: note: candidate: operator[](long int, const char*)
Код: Выделить всё
child& operator[](const int& num){
return (*this)[uint32_t(num)];
}
Я не совсем понимаю, почему мне нужно добавлять два варианта каждой перегрузки (string/char* и uint32_t/int)
Подробнее здесь: https://stackoverflow.com/questions/793 ... verloading