sha*_*oth 75
像这样的东西:
class Class {
// visibility will default to private unless you specify it
struct Struct {
//specify members here;
};
};
Run Code Online (Sandbox Code Playgroud)
Afr*_*ief 50
在某些头文件中声明class&nested struct
class C {
// struct will be private without `public:` keyword
struct S {
// members will be public without `private:` keyword
int sa;
void func();
};
void func(S s);
};
Run Code Online (Sandbox Code Playgroud)
如果你想分离实现/定义,可能在一些CPP文件中
void C::func(S s) {
// implementation here
}
void C::S::func() { // <= note that you need the `full path` to the function
// implementation here
}
Run Code Online (Sandbox Code Playgroud)
如果你想内联实现,其他答案将会很好.
tem*_*def 20
这里的其他答案演示了如何在类中定义结构。还有另一种方法可以做到这一点,那就是在类内部声明结构,但在外部定义它。这可能很有用,例如,如果结构体相当复杂,并且可能以某种方式独立使用,从而受益于在其他地方的详细描述。
其语法如下:
class Container {
...
struct Inner; // Declare, but not define, the struct.
...
};
struct Container::Inner {
/* Define the struct here. */
};
Run Code Online (Sandbox Code Playgroud)
您更常见的是在定义嵌套类而不是结构的上下文中看到这一点(一个常见的例子是为集合类定义迭代器类型),但我认为为了完整性,值得在这里炫耀。
就像是:
class Tree {
struct node {
int data;
node *llink;
node *rlink;
};
.....
.....
.....
};
Run Code Online (Sandbox Code Playgroud)