我運行下面的代碼將物件的父部分分配給子物件。但正如行內描述的那樣,c 風格向下轉換的行為出乎意料。那里發生了什么?請參考下面的評論。
struct A {
public:
int i{};
A() { std::cout<<"A constructor called\r\n"; }
~A() { std::cout<<"A destructor called\r\n"; }
};
struct B : public A {
B() { std::cout<<"B constructor called\r\n"; }
~B() { std::cout<<"B destructor called\r\n"; }
};
A a{};
B b{};
a.i = 1;
(A)b = a; // this code no effect and surprisingly the destructor of A is called.
// there was no compiler warning (g (Ubuntu 11.2.0-7ubuntu2) 11.2.0)
std::cout<<a.i<<std::endl;
std::cout<<b.i<<std::endl;
A& ra = b;
ra = a; // A portion of B is initialized as expected
std::cout<<b.i<<std::endl;
此代碼列印為
A 構造
函式呼叫
B 建構式呼叫
A 解構式呼叫 <-- 請注意這里
1
0
1
B 解構式呼叫
A 解構式呼叫
A 解構式呼叫
uj5u.com熱心網友回復:
魔法在這里:(A)b = a;
發生的事情是:
- 呼叫 A 的復制建構式并創建一個新的[class A object]。它是一個臨時物件,并在此宣告后銷毀。所以列印[一個名為 <-- 請注意這里的解構式]
- 在臨時物件上呼叫 A 的 operator=。它只影響臨時物件而不是原來的 b;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/352044.html
上一篇:在類別庫專案中使用類
