Reputation: 1
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
Upvotes: 0
Views: 361
Reputation: 14589
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
.
Upvotes: 0
Reputation: 122133
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.
Upvotes: 1
Reputation: 31
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.
Upvotes: 0