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

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


当前回答

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

其他回答

在c++中,struct和c++类只有一个区别,默认情况下,struct成员是public,类成员是private。

/*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;
}
struct HaveSome
{
   int fun;
   HaveSome()
   {
      fun = 69;
   }
};

我宁愿在构造函数中初始化,这样就不需要保持顺序。

正如其他答案所提到的,在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) {}
};

用法:

unsigned char *bptr = new unsigned char[1024];
blocknode *fblock = new blocknode(1024, btpr);

在c++中,struct和class都是相等的,除了struct的默认成员访问说明符是public和class有private。

在c++中使用struct的原因是c++是C的超集,必须向后兼容遗留的C类型。

例如,如果语言用户试图在他的c++代码中包含一些C头文件legacy-c.h,它包含struct Test {int x,y};struct Test的成员应该像C一样可以访问。

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