Basic Smalltalk Subclass

ⅰ亾dé卋堺 提交于 2019-12-11 06:46:09

问题


I am trying to create an extremely simple Vector class as a subclass of Array in Smalltalk. My code to create the class looks like this:

Array subclass: #Vector
Vector comment: 'I represent a Vector of integers'

Vector class extend [
new [
    | r |
    <category: 'instance creation'>
    r := super new.
    r init.
    ^r 
    ]
 ]

Vector extend [
init [
    <category: 'initialization'>
    ]
 ]

Obviously I haven't written any methods yet, but I'm just trying to get this part working first. After the class is created as above, if I type: v := Vector new: 4 I get error:

Object: Vector error: should not be implemented in this class, use #new instead
SystemExceptions.WrongMessageSent(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.WrongMessageSent class>>signalOn:useInstead: (SysExcept.st:1219)
Vector class(Behavior)>>new: (Builtins.st:70)
UndefinedObject>>executeStatements (a String:1)
nil

I had assumed that since it is a subclass of Array, I could create a Vector in this manner. What is the best way to go about doing this? Thanks!

Edit -- I figured it out. After reading deeper into the tutorial, I found I needed to include <shape: #pointer>


回答1:


Array is a special kind of class that has indexable instances of different lengths.

In GNU Smalltalk (which you appear to be using) the Array class is declared as:

ArrayedCollection subclass: Array [       
    <shape: #pointer>

To inherit this behaviour you can use:

Array subclass: Vector [<shape: #inherit>]

But in most cases it makes more sense to make a class that encapsulate an Array rather than a class that inherits from Array.

It's also worth pointing out that OrderedCollection is the Smalltalk equivalent of the vector container from C++ and Java.



来源:https://stackoverflow.com/questions/9474268/basic-smalltalk-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!