高階強制型別轉換 C (38)

2021-10-03 14:54:58 字數 1648 閱讀 7244

靜態物件強制型別轉換例如

右邊返回了乙個techcompany型別的指標,左邊定義了乙個company型別的指標,叫做company;

techcompany *techcompany = company;

這兩句話的意思是: 兩個相同型別的變數通過指標賦值,但是中間經過了乙個不同型別的指標,理論上是可行的,因為中間經過的和它們是繼承關係,但是編譯器不認,所以需要進行強制型別轉換。

解決方法

techcompany *techcompany = (techcompany*)company;

注意

動態物件強制型別轉換

dynamic_cast(value);
1/2 靜態物件強制型別轉換

#include

#include

using

namespace std;

class

company

;company::

company

(string thename,string product)

void company::

printinfo()

class

techcompany

:public company

;techcompany::

techcompany

(string thename,string product)

:company

(thename,product)

void techcompany::

printinfo()

intmain()

2/2 動態物件強制型別轉換

#include

#include

using

namespace std;

class

company

;company::

company

(string thename,string product)

void company::

printinfo()

class

techcompany

:public company

;techcompany::

techcompany

(string thename,string product)

:company

(thename,product)

void techcompany::

printinfo()

intmain()

else

delete company;

//釋放記憶體(此處company與techcompany兩個指標都指向techcompany定義的物件)

//所以釋放記憶體只需要釋放一次即可

company =

null

; techcompany =

null

;return0;

}

高階強制型別轉換

動態物件強制型別轉換 萬一被強制轉換的型別和目標型別結構完全不同,咋整?編譯器很笨的,它仍然將按照我們的 行事!這樣子的程式是相當危險的,隨時可能崩潰以及被崩潰。因為在類繼承關係之間跳來轉去 也就是對有關物件進行強制型別轉換 在物件導向的程式裡非常重要,所以c 程式設計師準備了幾個新的強制型別轉換操...

010 高階強制型別轉換

我們用傳統的強制型別轉換實現 把所需要的指標型別放在一對圓括號之間,然後寫出將被強制轉換的位址值。techcompany teccompany company 注意不能既刪除company,又刪除teccompany。因為強制型別轉換操作不會建立乙個副本拷貝,它只是告訴編譯器把有關變數解釋為另一種型...

C 38 整數遞增序列報數

先上題目 思路 這道題重點在於正確讀懂題目,最簡單理解是,給乙個數,輸出乙個字串。給的數是整數序列,這點很關鍵,序列!即第幾個數。分析示例的時候,其實就是說1 11,11 21,21 1211,1211 111221,這相當於乙個演變過程,假設我要求第五個,就要從第乙個開始演變到序列5。不說廢話了,...