Проблема компиляции с перегрузкой оператора индексаC++

Программы на C++. Форум разработчиков
Ответить Пред. темаСлед. тема
Anonymous
 Проблема компиляции с перегрузкой оператора индекса

Сообщение Anonymous »

Со следующим фрагментом кода

Код: Выделить всё

#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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C++»