我不确定我班上的申报顺序。我的编译器说error: "Foo" was not declared in this scope
。如果我更改了班级public
和private
部分的顺序,我最终会遇到同样的错误。此外,如果我想使用getFoo()
,并且我包含我的头文件,则结构Foo类型不可见,因为它是私有的。但是如果我再次把它放在公共范围内,那么公众就必须先私下来,因为否则myFoo
类型Foo
的声明不可能发生,因为Foo
没有被认定然而。
我在这里很困惑...感谢你的帮助!
/*MyClass.h*/
class MyClass
{
private:
struct Foo{
int bar;
};
Foo myFoo;
public:
Foo getFoo(){ return myFoo;}
};
答案 0 :(得分:3)
与公共或私人无关。您的内部类型必须在使用之前定义:
struct Foo
{
Bar bar() { return Bar(); } // ERROR
struct Bar {};
};
struct Foo
{
struct Bar {};
Bar bar() { return Bar(); } // OK
};
注意:关于private
类型的可访问性存在一些混淆。类型可以在类之外访问,它只是不能命名。因此,访问私有类型的代码是完全合法的:
class Foo
{
struct Bar {
void do_stuff() const {}
};
public:
Bar bar() { return Bar(); } // OK
};
int main()
{
Foo f;
f.bar().do_stuff(); // use temporary Bar object
// In C++11, you can even make a named instance
auto b = f.bar(); // instantiate a Bar object called b
b.do_stuff(); // use it
}
答案 1 :(得分:-1)
你的struct Foo应该是公开的,否则getFoo getter将不起作用,因为Foo只能在你的类中访问