File: structs.yo

package info (click to toggle)
c%2B%2B-annotations 10.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 10,536 kB
  • ctags: 3,247
  • sloc: cpp: 19,157; makefile: 1,521; ansic: 165; sh: 128; perl: 90
file content (45 lines) | stat: -rw-r--r-- 1,692 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Earlier we noted that functions can be part of tt(struct)s (see
section ref(FunctionInStruct)).  Such functions are called
    hi(member function)em(member functions).
This section briefly discusses how to define such functions.

The code fragment below shows a tt(struct) having data fields for a person's
name and address. A function tt(print) is included in the
tt(struct)'s definition:
        verb(
    struct Person
    {
        char name[80];
        char address[80];

        void print();
    };
        )
    When defining the member function tt(print) the structure's name
(tt(Person)) and the scope resolution operator (tt(::)) are used:
        verb(
    void Person::print()
    {
        cout << "Name:      " << name << "\n"
                "Address:   " << address << '\n';
    }
        )
    The implementation of tt(Person::print) shows how the fields of the
tt(struct) can be accessed without using the structure's type name. Here the
function tt(Person::print) prints a variable tt(name). Since tt(Person::print)
is itself a part of tt(struct) tt(person), the variable tt(name) implicitly
refers to the same type.

This tt(struct Person) could be used as follows:
        verb(
    Person person;

    strcpy(person.name, "Karel");
    strcpy(person.address, "Marskramerstraat 33");
    person.print();
        )
    The advantage of member functions is that the called function
automatically accesses the data fields of the structure for which it was
invoked. In the statement tt(person.print()) the object tt(person) is the
`substrate': the variables tt(name) and tt(address) that are used in the code
of tt(print) refer to the data stored in the tt(person) object.