C ++中的结构构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1127396/
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
Struct Constructor in C++?
提问by sth
Can a structhave a constructor in C++?
struct在 C++ 中可以有一个构造函数吗?
I have been trying to solve this problem but I am not getting the syntax.
我一直在尝试解决这个问题,但我没有得到语法。
回答by sth
In C++ the only difference between a classand a structis that members and base classes are private by default in classes, whereas they are public by default in structs.
在 C++ 中,aclass和 a之间的唯一区别struct是成员和基类在类中默认是私有的,而在结构中默认是公共的。
So structs can have constructors, and the syntax is the same as for classes.
所以结构体可以有构造函数,语法与类相同。
回答by nos
struct TestStruct {
int id;
TestStruct() : id(42)
{
}
};
回答by gitarooLegend
All the above answers technically answer the asker's question, but just thought I'd point out a case where you might encounter problems.
以上所有答案在技术上都回答了提问者的问题,但只是想我会指出一个您可能会遇到问题的情况。
If you declare your struct like this:
如果你像这样声明你的结构:
typedef struct{
int x;
foo(){};
} foo;
You will have problems trying to declare a constructor. This is of course because you haven't actually declared a struct named "foo", you've created an anonymous struct and assigned it the alias "foo". This also means you will not be able to use "foo" with a scoping operator in a cpp file:
尝试声明构造函数时会遇到问题。这当然是因为您实际上还没有声明一个名为“foo”的结构,您已经创建了一个匿名结构并为其分配了别名“foo”。这也意味着您将无法在 cpp 文件中使用带有作用域运算符的“foo”:
foo.h:
foo.h:
typedef struct{
int x;
void myFunc(int y);
} foo;
foo.cpp:
foo.cpp:
//<-- This will not work because the struct "foo" was never declared.
void foo::myFunc(int y)
{
//do something...
}
To fix this, you must either do this:
要解决此问题,您必须执行以下操作:
struct foo{
int x;
foo(){};
};
or this:
或这个:
typedef struct foo{
int x;
foo(){};
} foo;
Where the latter creates a struct called "foo" and gives it the alias "foo" so you don't have to use the structkeyword when referencing it.
后者创建一个名为“foo”的结构并为其提供别名“foo”,因此您struct在引用它时不必使用关键字。
回答by Chap
Yes, but if you have your structure in a union then you cannot. It is the same as a class.
是的,但是如果你的结构在一个联合中,那么你就不能。它与类相同。
struct Example
{
unsigned int mTest;
Example()
{
}
};
Unions will not allow constructors in the structs. You can make a constructor on the union though. This question relates to non-trivial constructors in unions.
联合将不允许在结构中使用构造函数。不过,您可以在联合上创建一个构造函数。这个问题与联合中的非平凡构造函数有关。
回答by Luqmaan
As the other answers mention, a struct is basically treated as a class in C++. This allows you to have a constructor which can be used to initialise the struct with default values. Below, the constructor takes szand bas arguments, and initializes the other variables to some default values.
正如其他答案所提到的,结构基本上被视为 C++ 中的一个类。这允许您拥有一个构造函数,该构造函数可用于使用默认值初始化结构。下面,构造函数将sz和b作为参数,并将其他变量初始化为一些默认值。
struct blocknode
{
unsigned int bsize;
bool free;
unsigned char *bptr;
blocknode *next;
blocknode *prev;
blocknode(unsigned int sz, unsigned char *b, bool f = true,
blocknode *p = 0, blocknode *n = 0) :
bsize(sz), free(f), bptr(b), prev(p), next(n) {}
};
Usage:
用法:
unsigned char *bptr = new unsigned char[1024];
blocknode *fblock = new blocknode(1024, btpr);
回答by GManNickG
Yes. A structure is just like a class, but defaults to public:, in the class definition and when inheriting:
是的。结构就像一个类,但public:在类定义和继承时默认为:
struct Foo
{
int bar;
Foo(void) :
bar(0)
{
}
}
Considering your other question, I would suggest you read through some tutorials. They will answer your questions faster and more complete than we will.
考虑到您的其他问题,我建议您阅读一些教程。他们会比我们更快、更完整地回答您的问题。
回答by SwDevMan81
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
I'd rather initialize inside the constructor so I don't need to keep the order.
我宁愿在构造函数内部初始化,所以我不需要保持顺序。
回答by heavyd
Yes structures and classes in C++ are the same except that structures members are public by default whereas classes members are private by default. Anything you can do in a class you should be able to do in a structure.
是的,C++ 中的结构和类是相同的,只是结构成员默认是公共的,而类成员默认是私有的。你在课堂上可以做的任何事情,你都应该可以在结构中做。
struct Foo
{
Foo()
{
// Initialize Foo
}
};
回答by Steve L
Note that there is one interesting difference (at least with the MS C++ compiler):
请注意,有一个有趣的区别(至少对于 MS C++ 编译器而言):
If you have a plain vanilla struct like this
如果你有一个像这样的普通香草结构
struct MyStruct {
int id;
double x;
double y;
} MYSTRUCT;
then somewhere else you might initialize an array of such objects like this:
然后在其他地方,您可能会像这样初始化一个此类对象的数组:
MYSTRUCT _pointList[] = {
{ 1, 1.0, 1.0 },
{ 2, 1.0, 2.0 },
{ 3, 2.0, 1.0 }
};
however, as soon as you add a user-defined constructor to MyStruct such as the ones discussed above, you'd get an error like this:
但是,一旦您将用户定义的构造函数添加到 MyStruct(例如上面讨论的那些)中,您就会收到如下错误:
'MyStruct' : Types with user defined constructors are not aggregate <file and line> : error C2552: '_pointList' : non-aggregates cannot be initialized with initializer list.
'MyStruct' : Types with user defined constructors are not aggregate <file and line> : error C2552: '_pointList' : non-aggregates cannot be initialized with initializer list.
So that's at least one other difference between a struct and a class. This kind of initialization may not be good OO practice, but it appears all over the place in the legacy WinSDK c++ code that I support. Just so you know...
所以这至少是结构和类之间的另一个区别。这种初始化可能不是好的 OO 实践,但它在我支持的旧版 WinSDK c++ 代码中无处不在。只是让你知道...


