在c++中,结构可以有构造函数吗?
我一直试图解决这个问题,但我没有得到语法。
在c++中,结构可以有构造函数吗?
我一直试图解决这个问题,但我没有得到语法。
当前回答
类、结构和联合在下表中简要描述。
其他回答
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
我宁愿在构造函数中初始化,这样就不需要保持顺序。
在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 TestStruct {
int id;
TestStruct() : id(42)
{
}
};
再举一个在构造函数中设置值时使用this关键字的例子:
#include <iostream>
using namespace std;
struct Node {
int value;
Node(int value) {
this->value = value;
}
void print()
{
cout << this->value << endl;
}
};
int main() {
Node n = Node(10);
n.print();
return 0;
}
用GCC 8.1.0编译。
在c++中,我们可以像类一样声明/定义结构,并拥有结构的构造函数/析构函数,并在其中定义变量/函数。 唯一的区别是定义的变量/函数的默认作用域。 除了上述差异之外,大多数情况下,您应该能够使用结构来模仿类的功能。