gpt4 book ai didi

c++ - 从 int* 到 int& 的转换

转载 作者:行者123 更新时间:2023-11-28 07:39:23 25 4
gpt4 key购买 nike

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

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&) [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::分配器,std::vector<_Tp, _Alloc>::reference = int&, std::vector<_Tp, _Alloc>::size_type = long unsigned int](((long unsigned int)i)) < pivot'qsort.h:31:9: 注意:候选人是:/usr/include/c++/4.6/bits/STL_pair.h:207:5: 注意:模板 bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2 >&)/usr/include/c++/4.6/bits/STL_iterator.h:291:5: 注意:template bool std::operator<(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)

最佳答案

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

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

关于c++ - 从 int* 到 int& 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16137746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com