在c++中,结构可以有构造函数吗?
我一直试图解决这个问题,但我没有得到语法。
在c++中,结构可以有构造函数吗?
我一直试图解决这个问题,但我没有得到语法。
当前回答
是的,c++中的结构和类是相同的,除了结构成员默认是公共的,而类成员默认是私有的。在类中可以做的任何事情,在结构中也应该可以做。
struct Foo
{
Foo()
{
// Initialize Foo
}
};
其他回答
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
我宁愿在构造函数中初始化,这样就不需要保持顺序。
struct TestStruct {
int id;
TestStruct() : id(42)
{
}
};
是的,在结构中有构造函数是可能的,这里有一个例子:
#include<iostream.h>
struct a {
int x;
a(){x=100;}
};
int main() {
struct a a1;
getch();
}
在c++中,类和结构之间的唯一区别是,成员和基类在类中默认是私有的,而在结构中默认是公共的。
struct可以有构造函数,语法和类一样。
再举一个在构造函数中设置值时使用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编译。