在函数 return 类型中推导出 class 类型 'Pair'
deduced class type 'Pair' in function return type
我需要用 C++ 编写字典。我写了一个包含 1 个键 + 值对的 Pair class 。我还写了一个包含向量对的字典。我想重载 [] 运算符,但它给了我一个错误。
template <typename TKey, typename TValue>
class Pair
{
public:
TKey key;
TValue value;
Pair()
{
this->key = 0;
this->value = 0;
}
Pair(TKey key, TValue value)
{
this->key = key;
this->value = value;
}
};
template <typename TKey, typename TValue>
class Dictionary
{
private:
vector<Pair<TKey, TValue>> pairs;
//...
public:
Pair operator[] (unsigned index)
{
return this->pairs[index];
}
//...
};
我遇到的错误:
deduced class type 'Pair' in function return type
我能用它做什么?
编译器需要知道您返回的是哪种 Pair
。
Pair<TKey, TValue> operator[] (unsigned index)
{
...
}
您可能想要添加类型别名以缩短声明:
template <typename TKey, typename TValue>
class Dictionary
{
public:
using EntryType = Pair<TKey, TValue>;
private:
vector<EntryType> pairs;
//...
public:
EntryType operator[] (unsigned index)
{
return this->pairs[index];
}
};
我需要用 C++ 编写字典。我写了一个包含 1 个键 + 值对的 Pair class 。我还写了一个包含向量对的字典。我想重载 [] 运算符,但它给了我一个错误。
template <typename TKey, typename TValue>
class Pair
{
public:
TKey key;
TValue value;
Pair()
{
this->key = 0;
this->value = 0;
}
Pair(TKey key, TValue value)
{
this->key = key;
this->value = value;
}
};
template <typename TKey, typename TValue>
class Dictionary
{
private:
vector<Pair<TKey, TValue>> pairs;
//...
public:
Pair operator[] (unsigned index)
{
return this->pairs[index];
}
//...
};
我遇到的错误:
deduced class type 'Pair' in function return type
我能用它做什么?
编译器需要知道您返回的是哪种 Pair
。
Pair<TKey, TValue> operator[] (unsigned index)
{
...
}
您可能想要添加类型别名以缩短声明:
template <typename TKey, typename TValue>
class Dictionary
{
public:
using EntryType = Pair<TKey, TValue>;
private:
vector<EntryType> pairs;
//...
public:
EntryType operator[] (unsigned index)
{
return this->pairs[index];
}
};