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

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


当前回答

在c++中,我们可以像类一样声明/定义结构,并拥有结构的构造函数/析构函数,并在其中定义变量/函数。 唯一的区别是定义的变量/函数的默认作用域。 除了上述差异之外,大多数情况下,您应该能够使用结构来模仿类的功能。

其他回答

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

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

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

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

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

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

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

struct Foo
{
    int bar;

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

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