2010-10-24 100 views
2

我試圖讓下面的代碼工作,但我找不到足夠好的文檔說明C++如何處理公有與私有繼承以允許我做我想做的事情。如果有人能解釋爲什麼我不能使用私有繼承訪問Parent::setSize(int)Parent::size或使用公共繼承訪問Parent::size。爲了解決這個問題,我需要在Parent中使用getSize()setSize()方法嗎?調用Parent方法並訪問父類中的私有變量?

class Parent { 
    private: 
     int size; 

    public: 
     void setSize(int s); 
}; 

void Parent::setSize(int s) { 
    size = s; 
} 

class Child : private Parent { 
    private: 
     int c; 

    public: 
     void print(); 
}; 

void Child::print() { 
    cout << size << endl; 
} 

int main() { 
    Child child; 

    child.setSize(4); 

    child.print(); 

    return 0; 
} 

回答

5

當您使用私有繼承時,基類的所有公共和受保護成員在派生類中都變爲私有。在你的例子中,setSizeChild中變爲私人,所以你不能從main調用它。

另外,size已在Parent中保密。一旦聲明爲private,成員始終對基類保持私有狀態,而不管繼承的類型如何。

+1

是的,和私有成員不繼承,這就是爲什麼你不能訪問 – 2010-10-24 17:48:17

+1

你描述什麼是錯的基類的私有成員,但沒有提供任何解決方案! – 2010-10-24 17:50:17

+0

@Ned Batchelder:這就是爲什麼我投你的答案。 :)我不確定OP究竟需要什麼,因爲否則正常的公共繼承會正常工作。 – casablanca 2010-10-24 17:53:05

0

您無法訪問私有數據 - 其他類的成員。如果你想訪問superclas的私有屬性,你應該通過公共或受保護的訪問器來實現。至於其他,請參閱@ casablanca的answer

10

更改父到:

protected: int size; 

如果你想從一個派生類訪問size成員,但不能從類外,那麼你要protected

更改孩子:

class Child: public Parent 

當你說class Child: private Parent,你說的應該是一個祕密,孩子是父母。您的main代碼清楚地表明您希望將Child作爲父項進行操作,因此它應該是公共繼承。

0
#include <iostream> 
using namespace std; 


class Parent { 
private: 
    int size; 

public: 
    void setSize(int s); 

    int fun() //member function from base class to access the protected variable 
    { 
     return size; 
    } 
}; 

void Parent::setSize(int s) { 
size = s; 
} 

class Child : private Parent { 
private: 
    int c; 

public: 
    void print(); 


    using Parent::setSize; //new code line 
    using Parent::fun;  //new code line 
}; 

void Child::print() { 
    cout << fun() << endl; 
} 

int main() { 
    Child child; 

    child.setSize(4); 

    child.print(); 

    return 0; 
} 
+2

歡迎來到Stack Overflow!我建議你[參觀](http://stackoverflow.com/tour)。在給出答案時,最好給出一些關於爲什麼你的答案是答案的解釋。 – 2017-01-26 01:49:15