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

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


当前回答

在c++中,类和结构之间的唯一区别是,成员和基类在类中默认是私有的,而在结构中默认是公共的。

struct可以有构造函数,语法和类一样。

其他回答

是的,在结构中有构造函数是可能的,这里有一个例子:

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

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

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

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

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关键字。

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

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

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

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