【问题标题】:Conversion from int* to int&从 int* 到 int& 的转换
【发布时间】:2013-04-14 19:15:12
【问题描述】:

我一直在尝试编译并使用 & 符号,但仍然无法弄清楚错误是什么。有什么想法吗?

qsort.cc:22:23: error: no matching function for call to ‘qsort<int>::quicksort(std::vector<int, std::allocator<int> >*)’
qsort.cc:22:23: note: candidate is:

qsort.h:16:6: note: void qsort<T>::quicksort(std::vector<T>&) [with T = int]
qsort.h:16:6: note:   no known conversion for argument 1 from ‘std::vector<int, std::allocator<int> >*’ to ‘std::vector<int, std::allocator<int> >&’

标题:

template <class T>
class qsort
{
public:

void quicksort(vector<T> &v);
void qusort(vector<T> &v, int left, int right);
void print(vector<T> &v);
};

template <class T>
void qsort<T>::quicksort(vector<T> &v)
{
qusort(&v, 0, 0);
}

template <class T>
void qsort<T>::print(vector<T> &v)
{
    for(int i = 0; i < v.size(); i++)
    {
    cout << v[i] << endl;
    }
}

主要:

int main()
{
qsort<int> asort;
vector<int> v;

v.push_back(2);
v.push_back(1);
v.push_back(7);
v.push_back(3);
v.push_back(8);
v.push_back(4);
v.push_back(0);
v.push_back(9);
v.push_back(5);
v.push_back(6);

asort.quicksort(&v);
asort.print(&v);

return 0;
}

从主函数调用中删除 & 后的更新错误(短版)

qsort.h:在成员函数“void quisort::qusort(std::vector&, int, int) [with T = int]”中: qsort.h:18:5: 从'void quisort::quicksort(std::vector&) [with T = int]'实例化

qsort.cc:22:22: 从这里实例化 qsort.h:27:38:错误:从“int”到“const char*”的无效转换 [-fpermissive] /usr/include/c++/4.6/bits/basic_string.tcc:214:5: 错误:初始化 'std::basic_string<_chart _traits _alloc>::basic_string(const _CharT*, const _Alloc&) 的参数 1 [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]' [-fpermissive]

qsort.h:18:5: 从“void quisort::quicksort(std::vector&) [with T = int]”实例化 qsort.cc:22:22:从这里实例化 qsort.h:31:9: 错误: '(& v)->std::vector<_tp _alloc>::operator[] [with _Tp = int, _Alloc = std:: 中的 'operator::reference = int&, std::vector<_tp _alloc>::size_type = long unsigned int](((long unsigned int)i)) &, const std::pair<_t1 _t2>&) /usr/include/c++/4.6/bits/stl_iterator.h:291:5: 注意:模板 bool std::operator&, const std::reverse_iterator<_iterator>&)

【问题讨论】:

  • 旁注:我建议您更改类名或将其放在命名空间中,因为名称 qsort 已被 std::qsort 的标准库实现占用。
  • @WhozCraig 谢谢,我没有意识到并改变了它。

标签: c++ vector type-conversion


【解决方案1】:

您的成员函数通过引用获取参数。它们不采用指针(地址运算符&amp; 返回的指针)。您只需要传递对象,引用就会绑定:

asort.quicksort(v);
asort.print(v);

【讨论】:

  • 问题是当我删除它时,我得到一个带有更多转换错误的大量错误块。
  • 应该是qusort(v, 0, 0);
  • @user2057191 qusort的签名是什么?
  • 这实际上是我的一个函数中的类型错误,但这解决了我的大部分问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 2020-01-15
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多