考慮一個從 stBase 繼承的簡單類 stDeriv。我很驚訝地發現我們無法通過 stBase 參考訪問 stDeriv 類成員。
下面的基本例子來說明我的觀點:
#include <fstream> // std::ifstream
#include <iostream> // std::cout
using namespace std;
typedef struct stBase
{
public:
virtual ~stBase() { ; }
stBase(int iB) { iB_ = iB; }
// Copy operator
stBase &operator=(const stBase &src)
{
iB_ = src.iB_;
return *this;
}
virtual void Hello() { cout << " Hello from stBase" << endl; }
private:
int iB_ = 0;
} stBase;
typedef struct stDeriv : public stBase
{
public:
int iD_ = 0;
stDeriv(int iB) : stBase(iB), iD_(0) { ; }
virtual void Hello() { cout << " Hello from stDeriv" << endl; }
// Copy operator
stDeriv &operator=(const stDeriv &src)
{
iD_ = src.iD_;
return *this;
}
} stDeriv;
int main(int, char *[])
{
int iErr = 0;
stBase aBase(0);
stDeriv aDeriv(1);
stDeriv &rDeriv = aDeriv;
stBase &rBase = aBase;
rBase.Hello(); // OK result : "Hello from stBase"
rDeriv.Hello(); // OK result : "Hello from stDeriv"
rBase = rDeriv; // KO!!! Cannot access to aDeriv.iD_ through rBase !!!
rBase.Hello(); // KO!!! result : "Hello from stBase" !!!
return iErr;
}
為什么我在“rBase = rDeriv;”之后無法通過 rBase 訪問 stDeriv::iD_ ?
uj5u.com熱心網友回復:
你不能像你那樣重新系結參考。rBase 已經有一個值,不能再分配給它。為什么 C 不允許重新系結參考?
所以只需做一個新的參考:
int main(int, char* [])
{
int iErr = 0;
stBase aBase(0);
stDeriv aDeriv(1);
stDeriv& rDeriv = aDeriv;
stBase& rBase = aBase;
rBase.Hello(); // OK result : "Hello from stBase"
rDeriv.Hello(); // OK result : "Hello from stDeriv"
// Make a new reference and all is fine
stBase& rBase2 = rDeriv;
rBase2.Hello(); // OK result : "Hello from stDeriv"
return iErr;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/325643.html
上一篇:Neo4j檢查單個節點是否存在多個關系,如果存在則回傳
下一篇:子建構式使用祖父建構式
