简体   繁体   中英

Wrapper around a class C++

suppose a C++ class has a constructor (among other constructors) of the form

Foo::Foo( FILE *fp ) { etc... }

Now I want create a wrapper class of the form

class WFoo {
      Foo::Foo A;
      Foo::Foo B;
 };

with constructor

WFoo::WFoo(FILE *fa, FILE *fb) {
      A(fa), B(fb);
}

What is wrong with the definition of WFoo? Thanks in advance.

This doesn't make any sense...

class WFoo {
      Foo::Foo A;
      Foo::Foo B;
 };

You mean...

class WFoo {
public:
      Foo A;
      Foo B;

      WFoo(FILE* fa, FILE* fb);
 };

WFoo::WFoo(FILE* fa, FILE* fb) :
    A(fa), B(fb)
{
}

Remember also that fields are initialized not in the order you read in the constructor but in the order they are declared in the class!

So...

#include <iostream>

struct XFoo
{
    XFoo(const char* s) { std::cout << s << std::endl; }
};

struct YBar
{
    XFoo a;
    XFoo b;

    YBar() : a("A"), b("B") {}
};

struct ZBar
{
    XFoo b;
    XFoo a;

    ZBar() : a("A"), b("B") {}
};


int main()
{
    YBar y;
    ZBar z;
    return 0;
}

will print out...

A
B
B
A

That's an initializer list but the syntax is off. Try:

WFoo::WFoo(FILE* fa, FILE* fb) : A(fa), B(fb)
  {
  }    

The syntax you're looking for is:

WFoo::WFoo(FILE *fa, FILE *fb) : A(fa), B(fb) { ... }

And, unless Foo is in a namespace called Foo and WFoo is not:

class WFoo {
   Foo A;
   Foo B;
};

If the code you've posted is psudocode, then there is nothing wrong with the definition of WFoo .

If, on the other hand, the code you've posted is not intended to be psudocode, but actual code you'd try to compile & run, then here is what's wrong with WFoo :

  1. You want Foo A; Not Foo::Foo A unless Foo is in a namespace called Foo (which would be bad)
  2. There is no convert constructor declaration.
  3. You aren't using the correct syntax for the initializer list.

This is what you want:

WFoo::WFoo(FILE* fa, FILE* fb)
:  A(fa), B(fb)
{
}

Note that the initializer list comes before the body of the constructor.

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