2 回答

TA貢獻(xiàn)1773條經(jīng)驗(yàn) 獲得超3個贊
它并不是C++的缺陷或是被設(shè)計(jì)者所忽視的問題。
當(dāng)我們使用虛函數(shù)的時(shí)候,它的訪問規(guī)則是在聲明的時(shí)候被確定的,而不是在被“子類重寫”(overridden)的時(shí)候,虛函數(shù)的訪問規(guī)則不會受到來自被重寫的子類函數(shù)的影響,更進(jìn)一步說,當(dāng)某個對象A的引用B(特指間接訪問)用來調(diào)用該對象的虛函數(shù)時(shí),對于該對象A的一切聲明信息,都取決于該對象的引用B,而不是這個引用所引用的對象A。
C++標(biāo)準(zhǔn)里有對該問題的具體說明:當(dāng)一個子類函數(shù)通過基類的指針調(diào)用時(shí),訪問權(quán)限取決于基類對該函數(shù)的聲明。
參考C++ Standard ISO/IEC 14882:2003(E) 第11.6節(jié):
11.6 Access to virtual functions [class.access.virt]
The access rules (clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [Example:
class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f()
{
D d;
B* pb = &d;
D* pd = &d;
pb->f(); //OK: B::f() is public,
// D::f() is invoked
pd->f(); //error: D::f() is private
}
—end example]
Access is checked at the call point using the type of the expression used to denote the object for which the member function is called (B* in the example above). The access of the member function in the class in which it was defined (D in the example above) is in general not known.
至少我們在程序編譯時(shí)無法獲知這個指針的值,它會指向何種位置。
經(jīng)驗(yàn):private僅僅是一個訪問限定符,它只限定函數(shù)和數(shù)據(jù)不能被“直接”訪問,而不擔(dān)保這些函數(shù)和數(shù)據(jù)會被通過其他方法間接地訪問到,在成員函數(shù)中返回一個類私有數(shù)據(jù)成員的引用也是這個道理。

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個贊
發(fā)現(xiàn)新大陸了呵呵,不錯,但是,它并不是C++的缺陷或是被設(shè)計(jì)者所忽視的問題。
當(dāng)我們使用虛函數(shù)的時(shí)候,它的訪問規(guī)則是在聲明的時(shí)候被確定的,而不是在被“子類重寫”(overridden)的時(shí)候,虛函數(shù)的訪問規(guī)則不會受到來自被重寫的子類函數(shù)的影響,更進(jìn)一步說,當(dāng)某個對象A的引用B(特指間接訪問)用來調(diào)用該對象的虛函數(shù)時(shí),對于該對象A的一切聲明信息,都取決于該對象的引用B,而不是這個引用所引用的對象A。
C++標(biāo)準(zhǔn)里有對該問題的具體說明:當(dāng)一個子類函數(shù)通過基類的指針調(diào)用時(shí),訪問權(quán)限取決于基類對該函數(shù)的聲明。
參考C++ Standard ISO/IEC 14882:2003(E) 第11.6節(jié):
11.6 Access to virtual functions [class.access.virt]
The access rules (clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [Example:
class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f()
{
D d;
B* pb = &d;
D* pd = &d;
pb->f(); //OK: B::f() is public,
// D::f() is invoked
pd->f(); //error: D::f() is private
}
—end example]
Access is checked at the call point using the type of the expression used to denote the object for which the member function is called (B* in the example above). The access of the member function in the class in which it was defined (D in the example above) is in general not known.
至少我們在程序編譯時(shí)無法獲知這個指針的值,它會指向何種位置。
經(jīng)驗(yàn):private僅僅是一個訪問限定符,它只限定函數(shù)和數(shù)據(jù)不能被“直接”訪問,而不擔(dān)保這些函數(shù)和數(shù)據(jù)會被通過其他方法間接地訪問到,在成員函數(shù)中返回一個類私有數(shù)據(jù)成員的引用也是這個道理。
另外,如果不是特殊的需要,一般來說,這并不是一個好的設(shè)計(jì),有點(diǎn)自找麻煩的味道!
- 2 回答
- 0 關(guān)注
- 257 瀏覽
添加回答
舉報(bào)