在c++中,结构可以有构造函数吗?

我一直试图解决这个问题,但我没有得到语法。


当前回答

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

其他回答

是的,但是如果你在工会中有你的结构,那么你就不能。它和类是一样的。

struct Example
{
   unsigned int mTest;
   Example()
   {
   }
};

工会将不允许在结构中使用构造函数。你可以在联合上创建一个构造函数。这个问题与联合中的非平凡构造函数有关。

是的,c++中的结构和类是相同的,除了结构成员默认是公共的,而类成员默认是私有的。在类中可以做的任何事情,在结构中也应该可以做。

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

再举一个在构造函数中设置值时使用this关键字的例子:

#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;
}

用GCC 8.1.0编译。

是的。结构就像一个类,但在类定义和继承时默认为public::

struct Foo
{
    int bar;

    Foo(void) :
    bar(0)
    {
    }
}

考虑到你的另一个问题,我建议你阅读一些教程。他们会比我们更快更全面地回答你的问题。

以上所有答案都严格地回答了提问者的问题,但我只是想指出一个可能会遇到问题的情况。

如果你像这样声明你的结构体:

typedef struct{
int x;
foo(){};
} foo;

在尝试声明构造函数时会遇到问题。当然,这是因为你实际上并没有声明一个名为“foo”的结构体,你创建了一个匿名结构体,并给它分配了别名“foo”。这也意味着你不能在cpp文件中使用"foo"和作用域操作符:

foo。:

typedef struct{
int x;
void myFunc(int y);
} foo;

foo.cpp:

//<-- This will not work because the struct "foo" was never declared.
void foo::myFunc(int y)
{
  //do something...
}

要解决这个问题,你必须这样做:

struct foo{
int x;
foo(){};
};

或:

typedef struct foo{
int x;
foo(){};
} foo;

后者创建了一个名为“foo”的结构体,并赋予其别名“foo”,因此在引用它时不必使用struct关键字。