简体   繁体   中英

c++ copying constructor for a composition class

I'm learning a c++ tutorial and having a hard time understanding part of the following code(see the commented part):

#include<iostream>
using namespace std;

class A
{
public:
    A(A&src)
    {
        cout<<"copying A..."<<endl;
    }
    A(void){}
    void Do(void)
    {
        cout<<"A is doing something"<<endl;
    }
};

class B
{
public:
    B(B&src)
    {
        cout<<"copying B..."<<endl;
    }
    B(void){}
    void Do(void)
    {
        cout<<"B is doing something"<<endl;
    }
};

class Compo
{
public:
    Compo(Compo &src):f1(f1),f2(f2)//???

    {
        cout<<"Copying Compo..."<<endl;
    }
    Compo(void){}
    A f1;
    B f2;

};

int main(void)
{
    Compo co1;
    Compo co2=co1;
    co2.f1.Do();
    co2.f2.Do();
}

So how does the compiler know which f1/f2 belongs to which Compo? Is there a way to make it more explicit?

thanks for the help

It doesn't, you're initializing f1 with itself, which can't lead to anything good. You want:

Compo(const Compo &src):f1(src.f1),f2(src.f2)//???
{
    cout<<"Copying Compo..."<<endl;
}

Another good example to turn on warnings . If you already have them on, pay attention to them.

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