在下面的代码中查看派生类的初始化列表。

class city {
    private:
        int id;
        int x;
        int y;
    public:
        int getID(){return id;};
        int getX(){return x;};
        int getY(){return y;};
        city(){
            id =0; x=0; y=0;
        }
        city(int idx, int xx, int yx){
            id = idx;
            x = xx;
            y = yx;
        }
        city(city* cityobj){
            id = cityobj->id;
            x = cityobj->x;
            y = cityobj->y;
        }
};

class city_detail : public city{
    private:
        city* neighbor;
    public:
        city_detail (city& neighborX, city& cityobj): city(cityobj){ // What???
                                                     /* ^ city(cityobj) and city(&cityobj) both work here */
            neighbor = &neighborX;
        }
        city* getN(){return neighbor;}
    };

int main(int argc, char*argv[]){

city LA(42, 1, 2);

city PDX(7, 3, 4);

city_detail LA_Detail(PDX, LA);

cout << "LA_Detail.ID: " << LA_Detail.getID() << endl; // works both ways
cout << "LA_Detail.x: " << LA_Detail.getX() << endl; // works both ways
cout << "LA_Detail.y: " << LA_Detail.getY() << endl; // works both ways

cout << "LA_Detail.NN: " << LA_Detail.getN() << endl; // returns address as it should

city * LA_neighbor = LA_Detail.getN();

cout << "LA_neighbor.ID: " << LA_neighbor->getID() << endl; // address is indeed valid
cout << "LA_neighbor.x: " << LA_neighbor->getX() << endl; // address is indeed valid
cout << "LA_neighbor.y: " << LA_neighbor->getY() << endl; // address is indeed valid


return 0;

}


为什么...: city(&cityobj)...: city(cityobj)都在这里工作?

我认为我不能做后者...: city(cityobj),并且我必须将一个地址传递给cityobj,因为基类的构造函数需要一个指针。

为什么我没有得到一些编译错误,例如:

cannot convert type city to city *吗?

显然,我无法在其他地方执行此操作,例如:

void getID(city* aCity){
        cout << "aCityID: " << aCity->getID() << endl;
        cout << "aCityX: " << aCity->getX() << endl;
}

void wrapper(city &aCity){
        getID(&aCity); // I must pass in the address here, else I get an error
}

city Greenway;
wrapper(Greenway);

最佳答案

它起作用的原因是,当您调用city(cityobj)时,它将使用编译器的隐式定义的副本构造函数;而当您调用city(&cityobj)时,它将使用您自己定义的转换构造函数:city(city* cityobj)

您不是要说neighbor(&cityobj)是吗?

关于c++ - 为什么我可以将引用作为参数传递给构造函数的指针参数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27110628/

10-12 15:43