为什么我可以将引用作为参数传递给构造函数的指针参数?

时间:2014-11-24 17:28:38

标签: c++ pointers constructor reference initializer-list

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

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); 

1 个答案:

答案 0 :(得分:2)

它的工作原理是,当你调用city(cityobj)时,它使用编译器隐式定义的复制构造函数,当你调用city(&cityobj)时,它使用你自己定义的转换构造函数:{{ 1}}。

你并不是说city(city* cityobj)对你说了什么?