考慮一個帶有一些變量的父類a,b,c。如果我從這個父類派生一個子類,子類是否知道變量a,b,c?如果是這樣,a,b,c的值是否在這個子類中保持不變?繼承的基礎知識
繼承的基礎知識
回答
子類將包含父類變量。
如果子類可以訪問它們是另一回事。變量需要至少有一個受保護的可訪問性,以便子類能夠訪問和/或使用它們。
如果將這些變量聲明爲私有? –
您不能從子類訪問它們,只能從父類中訪問它們。您可以在父類中創建一個公用函數來設置專用字段。 – martijn
OOP語言有來自外部和內部的類確定字段的可見性(「變量」)不同的訪問級別。 大部分面向對象程序設計語言至少有以下三種:private
,protected
和public
。如果你的基類變量是private
,派生類不能看到他們,如果他們是protected
他們可以(但非派生類不能),如果他們是public
每個人都可以看到他們 - 包括衍生和非相關的類。
當然,在基類的方法可以基類總是訪問私有變量 - 即使在派生類中新加入的方法無法看到它們。這裏是C++中的一個例子(其他OOP語言具有相似的語法)。
class Base {
private:
int a;
protected:
int b;
public:
int f() { a = 1; return a + b; }
}
class Derived : public Base {
public:
int g() {
// You cannot access a here, so this is illegal:
a = 2;
// You can access b here, so this is legal:
b = 2;
// Base::f, or parent::f() in Java, can access a, so this will return 1 + 2 = 3.
return Base::f();
}
}
class NonRelated {
void h() {
Derived d; // Create a derived object
// Both of these are illegal since neither a nor b is public:
d.a = 3;
d.b = 4;
// You *can* call both f() and g(), because they are both public.
// This will return 3.
// (Side note: in actual C++, calling d.f() would not be a good idea since a is not initialized).
d.g();
}
}
這些變量的值會在子類中保持不變嗎? –
我明白你在做什麼,但問題不明智。子類沒有變量的另一個副本:它擴展了基類,這意味着它繼承了它的所有變量和函數,但是如果實例化它,則不會獲得Base類的實例和Base + Derived類的實例, 或類似的東西。 – CompuChip
- 1. Python中的繼承基礎知識
- 2. C++,關於繼承的基礎知識
- 3. 繼承和子類基礎知識
- 4. 繼承基礎
- 5. PHP變量,類和繼承瞭解基礎知識
- 6. Ruby基礎知識
- 7. Makefile基礎知識
- 8. MPI基礎知識
- 9. SceneKit基礎知識
- 10. Appengine基礎知識
- 11. AOP基礎知識
- 12. Sitecore基礎知識
- 13. Feedburner基礎知識
- 14. jstree基礎知識
- 15. Angulartics2基礎知識
- 16. C++基礎知識
- 17. sqlite基礎知識
- 18. Threading基礎知識
- 19. 基礎SQL知識?
- 20. innerHTML基礎知識
- 21. Modernizr基礎知識
- 22. CS基礎知識
- 23. Swift基礎知識「!」 &「?」
- 24. Odoo - 繼承基礎模塊
- 25. CakePHP:Containable的基礎知識
- 26. Matlab的類基礎知識
- 27. backbone.js的基礎知識
- 28. Hector&Cassandra的基礎知識
- 29. Ada的T'Class基礎知識
- 30. Javascript dom 2基礎知識
請重新考慮您的問題,或者至少發佈您的代碼,如果可能的話。 – Ademar