0

I am trying to learn some OOP and I have a problem understanding the following program:

#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;

class A
{
public:
    A(int i) : m(i){}

    friend class B;

    friend void g_afiseaza_m();
private:
    int m;
};

class B
{
public:
    void afiseaza_m()
    {
        A a(250);
        cout<<"clasa B este prietena cu clasa A"<<endl<<" poate accesa membrul privat A::m"<<endl<<a.m<<endl;
    }
};

void g_afiseaza_m()
{
    A a(300);
    cout<<"functia g_afiseaza_m nu este un membru al clasei A dar este prieten"<<endl<<"poate accesa membrul privat A::m"<<endl<<a.m<<endl;
}

int main()
{
    B b;
    b.afiseaza_m();
    g_afiseaza_m();
    getch();
    return 0;
}

Can you please tell me what does this line do: public:A(int i) :m(i){} private: int m? I undestand that A is a constructor with the int parameter i, and that m is a private member of class A but I can't understand what is m(i) ? Is this a matter of syntax ?

4

3 回答 3

6

The m(i) in your constructor initializes the m member with value i.

Your example has the same outcome (and not behaviour) as

A(int i) {
    m = i;
}

Initializing members using initializer lists as in your example is more efficient because the member's constructor is called directly with parameter i whereas in the example above, the empty constructor of m is called and then m is assigned value i.

于 2012-11-01T16:04:47.103 回答
5

That's a constructor initializer list, it initializes the member m of the class with the specified value.

It's there to prevent initialization followed by immediate assignment in some cases (not here).

Some members can only be initilized in the initializer list - const members, reference members, types that aren't default-constructable.

于 2012-11-01T16:04:39.017 回答
5
A(int i) : m(i) {}
         ^^^^^^ this is called member-initialization list.

Here m(i) means m is being initialized with i.

If you have more members, say, x, y in your class, then you can write this:

A(int i) : m(i), x(i*10), y(i*i) {}

So all the 3 members are initialized before entering into the constructor body.

See these topics for more detailed answers:

于 2012-11-01T16:05:01.327 回答