gpt4 book ai didi

C++错误1错误C2664传递数组指针

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:58 25 4
gpt4 key购买 nike

我不明白如何解决这个问题,尝试了很多方法但没有解决方案。对此的帮助将不胜感激。谢谢。

Error 1 error C2664: 'void showAllBuses(const Bus *[],int)' : cannot convert argument 1 from 'Bus **' to 'const Bus *[]'

void showAllBuses(const Bus* pBuses[], int numBus) {
for (int i = 0; i < numBus; i++) {
cout << "Bus no ." << numBus << " details: " << endl;
cout << "Number: " << pBuses[i]->getNumber() << endl;
cout << "Driver name: " << pBuses[i]->getDriver().getName() << endl;
cout << "Driver experience(years): " << pBuses[i]->getDriver().getYearsDriving() << endl;
}
}

void listBusesWithYearsDriving(const Bus* pBuses[], int numBus, int drivingYears) {
for (int i = 0; i < numBus; i++) {
if (pBuses[i]->getDriver().getYearsDriving() >= drivingYears) {
cout << "Bus number: " << pBuses[i]->getNumber() << endl;
cout << "Driver name: " << pBuses[i]->getDriver().getName() << endl;
cout << "Driver experience: " << pBuses[i]->getDriver().getYearsDriving() << endl;
}
}
}

void removeDriver(Bus* pBuses[], int busPos) {
pBuses[busPos]->removeDriver();
}

void main() {
const int ASIZE = 4;
int drivingYears = 0;
Bus* buses = new Bus[ASIZE];
for (int i = 0; i < ASIZE; i++) {
addNewBus(&buses[i]);
cout << "Bus " << i << ": " << &buses[i] << endl;
}
showAllBuses(&buses, ASIZE);
cout << "Please enter a minimum years of experience to look for: " << endl;
cin >> drivingYears;
listBusesWithYearsDriving(&buses, ASIZE, drivingYears);
removeDriver(&buses, 0);
showAllBuses(&buses, ASIZE);
delete[] buses;
buses = nullptr;
cout << "\n\n";
system("pause");
}

最佳答案

对于任何类型TT*都可以隐式转换为const T*,但是T** 不能隐式转换为const T**。允许这样做可能会违反常量(1)

不过,T ** 可以 转换为 const T* const *。由于您的函数不会以任何方式修改数组,因此您可以像这样简单地更改其参数:

void showAllBuses(const Bus* const * pBuses, int numBus) {

请记住,在函数参数声明中,* 和最外层的 [] 是同义词。


(1) 代码如下:

const int C = 42;
int I = -42;
int *p = &I;
int *pp = &p;
const int **cp = pp; // error here, but if it was allowed:
*cp = &C; // no problem, *cp is `const int *`, but it's also `p`!
*p = 0; // p is &C!

关于C++错误1错误C2664传递数组指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29753606/

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