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

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


当前回答

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

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

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

其他回答

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

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

struct Foo
{
    int bar;

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

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

在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一样可以访问。

在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 Example
{
   unsigned int mTest;
   Example()
   {
   }
};

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