[英]Summing instance variable of objects [inside an array of objects] that have same one specific instance variable
[英]How to have an instance variable that is an array
我想用一個類創建一個Smalltalk應用程序,該類具有一個實例變量,該實例變量是一個數組,一個實例變量是該數組的大小。 理想情況下,我想在創建對象時對它們進行初始化,但是我需要在方法中手動對其進行初始化。
以下是我的代碼:
Object subclass: Student [
| numTests marks |
initialize [
numTests := 0.
marks := Array new: 10.
]
]
student := Student new.
student initialize.
但是我收到以下錯誤:
Object: Array new: 10 "<0x10b054b80>" error: method is responsibility of a subclass
我怎么解決這個問題?
您可能並不真的想要這樣做。 我通常使用Squeak派生函數和Array new:可以工作,但通常不是您想要的,因為Array是固定大小的(即您不能添加或刪除元素),因此通常使用OrderedCollection之類的東西。 同樣,通常,您不想將大小存儲在ivar中,而是在需要知道包含多少個元素時將其發送給您的集合。
我已經根據上述建議修改了您的代碼示例(還要注意,您不需要顯式發送#initialize,它是通過#new:完成的):
Object subclass: Student [
| marks |
initialize [
marks := OrderedCollection new: 10.
].
addMark: newMark [
marks add: newMark
].
removeMarkAt: markIdx [
marks removeAt: markIdx
].
size [
^ marks size
]
]
student := Student new.
如果您確實需要創建固定大小的數組,請更新您所使用的Smalltalk變體的問題,以便對實現有特定知識的人可以提供幫助。 您似乎遇到的問題是您的Smalltalk實現將Array視為抽象類,因此您需要實例化其子類以獲得固定大小的數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.