documented object constrs; endb works again

This commit is contained in:
Araq 2013-03-09 20:43:56 +01:00
commit a64d4dc35c
11 changed files with 152 additions and 143 deletions

View file

@ -46,8 +46,7 @@ Objects
Like tuples, objects are a means to pack different values together in a
structured way. However, objects provide many features that tuples do not:
They provide inheritance and information hiding. Because objects encapsulate
data, the ``()`` tuple constructor cannot be used to construct objects. So
the order of the object's fields is not as important as it is for tuples. The
data, the ``T()`` object constructor should only be used internally and the
programmer should provide a proc to initialize the object (this is called
a *constructor*).
@ -55,7 +54,6 @@ Objects have access to their type at runtime. There is an
``of`` operator that can be used to check the object's type:
.. code-block:: nimrod
type
TPerson = object of TObject
name*: string # the * means that `name` is accessible from other modules
@ -68,6 +66,8 @@ Objects have access to their type at runtime. There is an
student: TStudent
person: TPerson
assert(student of TStudent) # is true
# object construction:
student = TStudent(name: "Anton", age: 5, id: 2)
Object fields that should be visible from outside the defining module have to
be marked by ``*``. In contrast to tuples, different object types are
@ -161,12 +161,7 @@ An example:
of nkIf:
condition, thenPart, elsePart: PNode
var
n: PNode
new(n) # creates a new node
n.kind = nkFloat
n.floatVal = 0.0 # valid, because ``n.kind==nkFloat``
var n = PNode(kind: nkFloat, floatVal: 1.0)
# the following statement raises an `EInvalidField` exception, because
# n.kind's value does not fit:
n.strVal = ""
@ -288,30 +283,22 @@ Procedures always use static dispatch. For dynamic dispatch replace the
.. code-block:: nimrod
type
TExpr = object of TObject ## abstract base class for an expression
TLiteral = object of TExpr
PExpr = ref object of TObject ## abstract base class for an expression
PLiteral = ref object of PExpr
x: int
TPlusExpr = object of TExpr
a, b: ref TExpr
method eval(e: ref TExpr): int =
PPlusExpr = ref object of PExpr
a, b: PExpr
# watch out: 'eval' relies on dynamic binding
method eval(e: PExpr): int =
# override this base method
quit "to override!"
method eval(e: ref TLiteral): int = return e.x
method eval(e: ref TPlusExpr): int =
# watch out: relies on dynamic binding
return eval(e.a) + eval(e.b)
method eval(e: PLiteral): int = e.x
method eval(e: PPlusExpr): int = eval(e.a) + eval(e.b)
proc newLit(x: int): ref TLiteral =
new(result)
result.x = x
proc newPlus(a, b: ref TExpr): ref TPlusExpr =
new(result)
result.a = a
result.b = b
proc newLit(x: int): PLiteral = PLiteral(x: x)
proc newPlus(a, b: PExpr): PPlusExpr = PPlusExpr(a: a, b: b)
echo eval(newPlus(newPlus(newLit(1), newLit(2)), newLit(4)))