C++ 结构的函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13125944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Function for C++ struct
提问by John
Usually we can define a variable for a C++ struct, as in
通常我们可以为 C++ 结构定义一个变量,如
struct foo {
int bar;
};
Can we also define functions for a struct? How would we use those functions?
我们也可以为结构定义函数吗?我们将如何使用这些功能?
回答by Luchian Grigore
Yes, a struct
is identical to a class
except for the default access level (member-wise and inheritance-wise). (and the extra meaning class
carries when used with a template)
是的,除了默认访问级别(成员方式和继承方式)之外,astruct
与 aclass
相同。(以及class
与模板一起使用时的额外含义)
Every functionality supported by a class is consequently supported by a struct. You'd use methods the same as you'd use them for a class.
因此,一个类支持的每个功能都由一个结构支持。您将使用与在类中使用方法相同的方法。
struct foo {
int bar;
foo() : bar(3) {} //look, a constructor
int getBar()
{
return bar;
}
};
foo f;
int y = f.getBar(); // y is 3
回答by 0x499602D2
Structs can have functions just like classes. The only difference is that they are public by default:
结构可以像类一样具有功能。唯一的区别是它们默认是公开的:
struct A {
void f() {}
};
Additionally, structs can also have constructors and destructors.
此外,结构体也可以有构造函数和析构函数。
struct A {
A() : x(5) {}
~A() {}
private: int x;
};