1

I'm working on a project with a pre-made .hpp file with all the declarations and stuff.

A struct is declared in the private part of the class, along with some private members.

I need to create an array with the type of the struct in my .cpp file.

//.hpp

private:
     struct foo
     {
          std::string a;
          unsigned int b;
     };

     std::string* x;
     unsigned int y;

//.cpp

unsigned int returny()
{
     return y;    // No errors
}

foo newArray[10]; // Compile time error; unknown type name

Why is it that I can return y, which is also private, but not make an array out of the struct foo?

How can I fix this? (I'm in an introductory C++ class... so hopefully there's a simple solution)

Daniel
  • 21
  • 1
  • 1
  • 2
  • 2
    Please paste complete reproducible code... – ravi Nov 30 '14 at 07:52
  • If `newArray` is inside a member function, you should not get that error. Please post a complete example. If it's not inside a member function, you're probably doing it wrong. (If it's an introductory C++ class and you were given the header, you're supposed to complete the exercise *without* creating an array of the struct outside the class.) – molbdnilo Nov 30 '14 at 08:33

2 Answers2

2

There are couple of issues.

  1. You can't use a type that's defined in the private section of class like you are trying.

  2. The nested type can be used by specifying the appropriate scope.

    EnclosingClass::foo newArray[10];
    

    But this will work only if foo is defined in the public section of EnclosingClass.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

you should define the struct int the outside of the class like this

struct Foo
     {
          std::string a;
          unsigned int b;
     };

class A {
private:
Foo foo;
...
}
pang1567
  • 125
  • 7