在c++中,结构可以有构造函数吗?
我一直试图解决这个问题,但我没有得到语法。
在c++中,结构可以有构造函数吗?
我一直试图解决这个问题,但我没有得到语法。
当前回答
语法与c++中的类是一样的。如果你知道在c++中创建构造函数,那么在struct中也是一样的。
struct Date
{
int day;
Date(int d)
{
day = d;
}
void printDay()
{
cout << "day " << day << endl;
}
};
Struct在c++中可以把所有东西都作为类。如前所述,区别只是默认情况下c++成员具有私有访问权限,但在结构中它是公共访问权限。但是根据编程考虑,对于仅数据结构使用struct关键字。对于同时具有数据和函数的对象使用class关键字。
其他回答
是的,在结构中有构造函数是可能的,这里有一个例子:
#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)
{
}
}
考虑到你的另一个问题,我建议你阅读一些教程。他们会比我们更快更全面地回答你的问题。
是的,c++中的结构和类是相同的,除了结构成员默认是公共的,而类成员默认是私有的。在类中可以做的任何事情,在结构中也应该可以做。
struct Foo
{
Foo()
{
// Initialize Foo
}
};
struct HaveSome
{
int fun;
HaveSome()
{
fun = 69;
}
};
我宁愿在构造函数中初始化,这样就不需要保持顺序。
再举一个在构造函数中设置值时使用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编译。