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

标签 c++

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

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**。允许这样做可能会违反 constness(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/

相关文章:

c++ - MSVC 2008 Express Edition 编译器做什么和不做什么

c++ - 如何将 Windows 窗体应用程序 (C++) 设置为具有 Aero/Glass 背景?

c++ - 文件传输返回奇怪的字符

c++ - 递归 Finbonacci 优化

c++ - vector vector 的迭代器无法处理一维 vector

c++ - 将无符号字符数组转换为整数

c++ - 如何使用 C++ 库算法分区函数进行快速排序?

c++ - 多个构造函数的析构函数

c++ - 在 map 中使用 std::thread::id 以获得线程安全

c++ - 在C++中相应地乘以 vector 元素