简体   繁体   中英

nested class or struct in a class

Code goes first:

//.h file

class A
{
    public:
        A();
        B makeB(int);  //question 1
    //protected:
        struct B {
            int _id;
            B(int id);
        }
};

//.cpp file

A::A()
{  cout<<"A ctor\n"; }

B A::makeB(int id)  //question 2
{  return B(id); }

2 questions:

1.Should I put makeB() function after the definition of struct B?

2.In .cpp file, should prefix every B with A:: ?

PS: 1.If makeB function doesn't deal with B instances, but B pointers or refs, can I put a forward decl of struct B in front of makeB? (I just don't want put the definition of struct B in front of mem-funcs).

This compiles fine:

class A
{
 public:
    struct B;

    A();
    B makeB(int);  //question 1

    struct B {
        int _id;
        B(int id) {};
    };
};

A::A() {}

A::B A::makeB(int id)  //question 2
{  return B(id); }

Q1. Yes (it needs to know the size of struct B)

QPS1. Yes (if it only uses pointers to B, it does not need to know the size)

Q2. Also, you can write "using A::B" and then, use "B" as usual.

Yes and yes. Otherwise, this should be hard to compile.

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