全國最多中醫師線上諮詢網站-台灣中醫網
發文 回覆 瀏覽次數:3442
推到 Plurk!
推到 Facebook!

物件繼承後可以使用父代私有函數?

答題得分者是:Coffee
chenyk
高階會員


發表:14
回覆:95
積分:171
註冊:2002-07-08

發送簡訊給我
#1 引用回覆 回覆 發表時間:2010-10-26 09:43:01 IP:125.230.xxx.xxx 訂閱
最近在練習物件繼承,以下是我測試的程式碼,我使用D7可以正常執行,TBclass 繼承於 TAclass,
TBclass 居然可以使用 TAclass 的私有函數,這跟書上描述的似乎不太一樣
如果把兩個物件分成兩個 Unit File各自儲存,則D7會發出Undeclared identifier: 'Test' 的錯誤訊息。

難道多個物件放在同個檔案,互相繼承後函數就不受物件規則限制嗎?還是說我的觀念上有錯誤?

unit Unit2;
interface
uses
Dialogs;
type
TAclass = class
private
procedure Test(const sMsg: string);
public
end;
TBclass = class(TAclass)
private
public
procedure ShowMsg(const sMsg: string);
end;
implementation
procedure TAclass.Test(const sMsg: string);
begin
ShowMessage(sMsg);
end;
procedure TBclass.ShowMsg(const sMsg: string);
begin
Test(sMsg);
end;
Coffee
版主


發表:31
回覆:878
積分:561
註冊:2006-11-15

發送簡訊給我
#2 引用回覆 回覆 發表時間:2010-10-26 10:10:58 IP:220.130.xxx.xxx 訂閱
我的印象中沒記錯的話,不用繼承也可以,在同一個unit裡面的class可以呼叫到其它class的privarte method。
這個意義就跟C 的friend修飾字是類似的,但坦白說我沒有這樣使用過。

===================引 用 chenyk 文 章===================
最近在練習物件繼承,以下是我測試的程式碼,我使用D7可以正常執行,TBclass 繼承於 TAclass,
TBclass 居然可以使用 TAclass 的私有函數,這跟書上描述的似乎不太一樣
如果把兩個物件分成兩個 Unit File各自儲存,則D7會發出Undeclared identifier: 'Test' 的錯誤訊息。

難道多個物件放在同個檔案,互相繼承後函數就不受物件規則限制嗎?還是說我的觀念上有錯誤?

unit Unit2;
interface
uses
Dialogs;
type
TAclass = class
private
procedure Test(const sMsg: string);
public
end;
TBclass = class(TAclass)
private
public
procedure ShowMsg(const sMsg: string);
end;
implementation
procedure TAclass.Test(const sMsg: string);
begin
ShowMessage(sMsg);
end;
procedure TBclass.ShowMsg(const sMsg: string);
begin
Test(sMsg);
end;
------
不論是否我發的文,在能力範圍皆很樂意為大家回答問題。
為了補我的能力不足之處,以及讓答案可以被重複的使用,希望大家能儘量以公開的方式問問題。
在引述到我的文時自然會儘量替各位想辦法,謝謝大家!
chenyk
高階會員


發表:14
回覆:95
積分:171
註冊:2002-07-08

發送簡訊給我
#3 引用回覆 回覆 發表時間:2010-10-26 10:59:04 IP:125.230.xxx.xxx 訂閱
 感謝大大答覆

我測了一下,沒有繼承並沒有辦法使用對方的私有函數。
看了下網路的關於 friend 的資料,的確跟我的問題相似
受教了。
aftcast
站務副站長


發表:81
回覆:1485
積分:1763
註冊:2002-11-21

發送簡訊給我
#4 引用回覆 回覆 發表時間:2010-10-26 22:40:52 IP:220.135.xxx.xxx 訂閱
幫忙補充一下:

A private method is (unit) private. What you need is a protected method. Protected methods can be accessed by any class that inherits from the base class even if they are in different units. User code can't access them (unless he inherits from the class).

此如同發問者一樣,同一個unit是可以存取private的。因為早期的delphi的pravate是指 unit 的範籌而非一般物件導向(如java,c )一般。

而重點來了…

自從delphi2005版後…

there's also aThe private keyword actually creates a " friendship" relationship between classes in the same unit. The strict private declaration creates a true private field, not viewable by any other class, not even classes in the same unit.


我是今天查了才發現…原來delphi7(含)以前是這樣在處理private的。

和大家分享一下。
------


蕭沖
--All ideas are worthless unless implemented--

C++ Builder Delphi Taiwan G+ 社群
http://bit.ly/cbtaiwan
系統時間:2024-04-26 12:19:43
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!