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

时间:2015-04-20 16:41:07

标签: c++

我不明白如何解决这个问题,尝试过许多方法但没有解决方案。对它的帮助将非常感激。感谢。

  

错误1错误C2664:'void showAllBuses(const Bus *[],int)':无法将参数1从'Bus **'转换为'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");
}

1 个答案:

答案 0 :(得分:2)

对于任何类型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!