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

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


当前回答

类、结构和联合在下表中简要描述。

其他回答

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

语法与c++中的类是一样的。如果你知道在c++中创建构造函数,那么在struct中也是一样的。

struct Date
{
    int day;

    Date(int d)
    {
        day = d;
    }

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

Struct在c++中可以把所有东西都作为类。如前所述,区别只是默认情况下c++成员具有私有访问权限,但在结构中它是公共访问权限。但是根据编程考虑,对于仅数据结构使用struct关键字。对于同时具有数据和函数的对象使用class关键字。

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

注意这里有一个有趣的区别(至少在MS c++编译器中):


如果你有一个像这样的普通结构

struct MyStruct {
   int id;
   double x;
   double y;
} MYSTRUCT;

然后在其他地方,你可以初始化一个这样的对象数组:

MYSTRUCT _pointList[] = { 
   { 1, 1.0, 1.0 }, 
   { 2, 1.0, 2.0 }, 
   { 3, 2.0, 1.0 }
};

然而,一旦你添加一个用户定义的构造函数到MyStruct,比如上面讨论的那些,你会得到这样一个错误:

'MyStruct':带有用户定义构造函数的类型不是聚合的 <文件和行>:错误C2552:“_pointList”:非聚合不能 使用初始化列表初始化。

这至少是结构体和类的另一个区别。这种初始化可能不是好的OO实践,但它在我支持的遗留WinSDK c++代码中随处可见。只是想让你知道…

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

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

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