指標和引用的upcasting__閱讀筆記

來源:互聯網
上載者:User


指標和引用的upcasting

除了在函數調用時編譯器可以實現自動轉換外,在進行指標或者引用賦值時也可以自動轉換。和函數調用一樣,這兩種情況都不需要顯式的強制轉換。

Wind w;

Instrument* ip = &w; // Upcast

Instrument& ir = w; // Upcast
危機

在upcast的時候會失去類型資訊,如下編譯器只能將ip作為Instrument的指標來調用

Wind w;

Instrument* ip = &w;

ip->play(middleC);

此時調用的是基類的Instrument::play( )而非本意Wind::play( ).,這種問題可以通過物件導向的編程技術的第三個裡程碑多態polymorphism來解決,在C++中是通過虛函數來實現的。

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

採用多態技術是值傳遞和地址傳遞有很大的區別,因為地址大小總是一樣的;傳遞衍生類別的地址和基類的地址是一樣的,因為衍生類別中包含了基類。值傳遞時,派生對象將剝離只剩下基類部分。

//: C15:ObjectSlicing.cpp

#include <iostream>

#include <string>

using namespace std;

class Pet {

string pname;

public:

Pet(const string& name) : pname(name) {}

virtual string name() const { return pname; }

virtual string description() const {

return "This is " + pname;

}

};

class Dog : public Pet {

string favoriteActivity;

public:

Dog(const string& name, const string& activity)

: Pet(name), favoriteActivity(activity) {}

string description() const {

return Pet::name() + " likes to " +

favoriteActivity;

}

};

void describe(Pet p) { // Slices the object

cout << p.description() << endl;

}

int main() {

Pet p("Alfred");

Dog d("Fluffy", "sleep");

describe(p);

describe(d);

} ///:~

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

This is Alfred

This is Fluffy

 

 

兩個原因:

首先,當調用describe時,只有Pet大小的東西在棧上分配釋放,因此多餘的部分將被剝離;

其次,因為是值傳遞,編譯器知道具體的資料類型,將調用pet的拷貝建構函式,其將VPTR初始化為PET的VTABLE,然後將dog的基類部分拷貝至p中,因此p將變成完完全全的pet對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.