简体   繁体   中英

C++: Access private member vector of structs from other class

from a similiar question here I tried the solution

class A {
 ...
  public:

    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
};

but always get error: 'DataStruct' was not declared in this scope. DataStruct and vec_A are defined in private section, below public section, in same class.

Please, could someone help me.

Regards, Thomas

I suppose you have code similar to the following example:

#include <iostream>
struct foo {
    private:
       struct bar {
           void barbar() { std::cout << "hello";}
       };
    public:
    bar foobar() { return bar{}; }
};

int main() {
    foo f;
    foo::bar x = f.foobar();
    x.barbar();
}

It has an error:

<source>: In function 'int main()':
<source>:13:10: error: 'struct foo::bar' is private within this context
   13 |     foo::bar x = f.foobar();
      |          ^~~
<source>:4:15: note: declared private here
    4 |        struct bar {
      |               ^~~

because bar is private in foo . However, that doesnt mean that you cannot use it outside of foo . You can use auto :

int main() {
    foo f;
    auto x = f.foobar();
    x.barbar();
}

Or decltype :

int main() {
    foo f;
    using bar_alias = decltype(f.foobar());
    bar_alias x = f.foobar();
    x.barbar();
}

You cannot access the name DataType but you can use auto and you can get an alias for the type. This also works for a std::vector<DataType> , only some more boilerplate would be required to get your hands on DataType directly.

You are trying to create a vector out of the Datatype "DataStruct". Are you sure that you wrote the Class/or implemented it? It could be only a variable. You know that you actually have to put a Datatype in it like int,bool,string. It defines what datatype the specific variables in the vector are made of.

Firstly, the the return type declarator part std::vector<DataStruct> requires a complete type in this context. That's what that error signifies. Class definition block can look forward for identifiers and signatures of members, but it cannot look for type definition.

Class A is not complete until its closing brace. Consecutively, nested classes defined aren't complete until theirs closing braces. Following declaration is correct one:

class A 
{
private:
    struct DataStruct {
    }; // a complete type
public:
    // Give read-only access to vec_A
    const std::vector<DataStruct> & getVector() const {
        return vec_A;
    }
private:   
   std::vector<DataStruct> vec_A;
};

In any other case you could forward declare it as struct A::DataStruct .

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