简体   繁体   中英

C++ - member function and array of objects

When I have a class and create one object, it's simple to call a member function. It's something like this:

class Foo
{
    ...
public:
    void function();
}

void Foo::function()
{
    ...
}

int main()
{
    Foo f1;
    f1.function();
}

But how should I call a member function when I'm going to create an array of objects?

class Foo
{
    ...
public:
    void function();
}

void Foo::function()
{
    ...
}

int main()
{
    Foo *f1;
    ???
}

Object:

A a;
a.foo()

Pointer:

A *a;
a->foo();

Table/"Array":

A a[10];
a[0].foo()

Those are really basics available in every free c++ course.

try this

int main()
{
    Foo arrayOfFoo[5];
    arrayOfFoo[0].function();
}

This creates 5 objects of type Foo in an array called arrayOfFoo Then it performs the method function() on the object at array index 0 in the array arrayOfFoo .

First you have to create an array of objects . You can do so by Foo f1[100]; statement in main .

I chose the random number 100, you can choose any. Also , to access the member function you have to use the dot operator. For eg

f1[1].function()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM