简体   繁体   English

C ++中的结构构造函数?

[英]Struct Constructor in C++?

Can a struct have a constructor in C++? struct可以在 C++ 中具有构造函数吗?

I have been trying to solve this problem but I am not getting the syntax.我一直在尝试解决这个问题,但我没有得到语法。

In C++ the only difference between a class and a struct is that members and base classes are private by default in classes, whereas they are public by default in structs.在 C++ 中, classstruct之间的唯一区别是成员和基类在类中默认是私有的,而在结构中默认是公共的。

So structs can have constructors, and the syntax is the same as for classes.所以结构体可以有构造函数,语法与类相同。

struct TestStruct {
        int id;
        TestStruct() : id(42)
        {
        }
};

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".这当然是因为您实际上还没有声明一个名为“foo”的结构,您已经创建了一个匿名结构并为其分配了别名“foo”。 This also means you will not be able to use "foo" with a scoping operator in a cpp file:这也意味着您将无法在 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 struct keyword when referencing it.后者创建一个名为“foo”的结构并为其提供别名“foo”,因此您在引用它时不必使用struct关键字。

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. 这个问题与联合中的非平凡构造函数有关。

Class, Structure and Union is described in below table in short.类、结构和联合在下表中简要描述。

在此处输入图片说明

As the other answers mention, a struct is basically treated as a class in C++.正如其他答案所提到的,结构基本上被视为 C++ 中的一个类。 This allows you to have a constructor which can be used to initialise the struct with default values.这允许您拥有一个构造函数,该构造函数可用于使用默认值初始化结构。 Below, the constructor takes sz and b as arguments, and initializes the other variables to some default values.下面,构造函数以szb作为参数,并将其他变量初始化为一些默认值。

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);

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.他们会比我们更快、更完整地回答您的问题。

struct HaveSome
{
   int fun;
   HaveSome()
   {
      fun = 69;
   }
};

I'd rather initialize inside the constructor so I don't need to keep the order.我宁愿在构造函数内部初始化,所以我不需要保持顺序。

In c++ struct and c++ class have only one difference by default struct members are public and class members are private.c++ 结构c++ 类中,默认结构成员只有一个区别是公共的,而类成员是私有的。

/*Here, C++ program constructor in struct*/ 
#include <iostream>
using namespace std;

struct hello
    {
    public:     //by default also it is public
        hello();    
        ~hello();
    };

hello::hello()
    {
    cout<<"calling constructor...!"<<endl;
    }

hello::~hello()
    {
    cout<<"calling destructor...!"<<endl;
    }

int main()
{
hello obj;      //creating a hello obj, calling hello constructor and destructor 

return 0;
}

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.

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.这种初始化可能不是好的 OO 实践,但它在我支持的旧版 WinSDK c++ 代码中无处不在。 Just so you know...只是让你知道...

Yes structures and classes in C++ are the same except that structures members are public by default whereas classes members are private by default.是的,C++ 中的结构和类是相同的,只是结构成员默认是公共的,而类成员默认是私有的。 Anything you can do in a class you should be able to do in a structure.你在课堂上可以做的任何事情,你都应该可以在结构中做。

struct Foo
{
  Foo()
  {
    // Initialize Foo
  }
};

One more example but using this keyword when setting value in constructor:还有一个例子,但在构造函数中设置值时使用关键字:

#include <iostream>

using namespace std;

struct Node {
    int value;

    Node(int value) {
        this->value = value;
    }

    void print()
    {
        cout << this->value << endl;
    }
};

int main() {
    Node n = Node(10);
    n.print();

    return 0;
}

Compiled with GCC 8.1.0.用 GCC 8.1.0 编译。

Syntax is as same as of class in C++.语法与 C++ 中的类相同。 If you aware of creating constructor in c++ then it is same in struct.如果您知道在 C++ 中创建构造函数,那么它在 struct 中是相同的。

struct Date
{
    int day;

    Date(int d)
    {
        day = d;
    }

    void printDay()
    {
        cout << "day " << day << endl;
    }
};

Struct can have all things as class in c++. Struct 可以将所有东西作为 C++ 中的类。 As earlier said difference is only that by default C++ member have private access but in struct it is public.But as per programming consideration Use the struct keyword for data-only structures.如前所述,区别仅在于默认情况下 C++ 成员具有私有访问权限,但在结构中它是公共的。但根据编程考虑,将 struct 关键字用于仅数据结构。 Use the class keyword for objects that have both data and functions.对同时具有数据和函数的对象使用 class 关键字。

In C++ both struct & class are equal except struct's default member access specifier is public & class has private .在 C++ 中, structclass是相等的,除了struct's默认成员访问说明符是public & class 有private

The reason for having struct in C++ is C++ is a superset of C and must have backward compatible with legacy C types .在 C++ 中使用struct的原因是 C++ 是 C 的超集,并且必须与legacy C types向后兼容。

For example if the language user tries to include some C header file legacy-ch in his C++ code & it contains struct Test {int x,y};例如,如果语言用户试图在他的 C++ 代码中包含一些 C 头文件legacy-ch & 它包含struct Test {int x,y}; . . Members of struct Test should be accessible as like C. struct Test成员应该像 C 一样可以访问。

Yes it possible to have constructor in structure here is one example:是的,可以在结构中使用构造函数,这是一个示例:

#include<iostream.h> 
struct a {
  int x;
  a(){x=100;}
};

int main() {
  struct a a1;
  getch();
}

In C++, we can declare/define the structure just like class and have the constructors/destructors for the Structures and have variables/functions defined in it.在 C++ 中,我们可以像类一样声明/定义结构,并拥有结构的构造函数/析构函数,并在其中定义变量/函数。 The only difference is the default scope of the variables/functions defined.唯一的区别是定义的变量/函数的默认范围。 Other than the above difference, mostly you should be able to imitate the functionality of class using structs.除了上述差异之外,大多数情况下您应该能够使用结构来模仿类的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM