Fork me on GitHub

C++的结构体使用

C++的结构体

一、struct的演变

C中的struct不能包含任何函数。因为在面向过程的编程中,数据和数据操作是分开的,struct作为一种数据类型,其中不能定义函数进行操作行为。

struct A
{
	int a;
	int b;
	//成员列表
};

而C++中的struct可以包含成员函数,在兼容C的同时也符合面向对象编程需要

二、C++struct使用

除了成员变量与成员函数外,C++中的struct可以写构造函数

结构体中构造函数的写法

结构体名(参数列表):初始化列表{ 函数体}

struct foo{
	int numb;
	string str;
	foo(int a,string s):numb(a),str(s){}//构造函数结尾是没有分号的
}; 

具体使用

在建立结构体数组时,如果只写了带参数的构造函数将会出现数组无法初始化的错误!!!

安全写法

struct node{
    int data;
    string str;
    char x;
  node() :x(), str(), data(){} //无参数的构造函数数组初始化时调用
  node(int a, string b, char c) :data(a), str(b), x(c){}//有参构造
}N[10];

下面我们分别使用默认构造和有参构造,以及自己手动写的初始化函数进行会结构体赋值

并观察结果

测试用例如下:

#include <iostream>
#include <string>
using namespace std;
struct node{
	int data;
	string str;
	char x;
	//自己写的初始化函数
	void init(int a, string b, char c){
		this->data = a;
		this->str = b;
		this->x = c;
	}
	node() :x(), str(), data(){}
	node(int a, string b, char c) :x(c), str(b), data(a){}
}N[10];
int main()
{
	  N[0] = { 1,"hello",'c' };  
	  N[1] = { 2,"c++",'d' };    //无参默认结构体构造体函数
	  N[2].init(3, "java", 'e'); //自定义初始化函数的调用
	  N[3] = node(4, "python", 'f'); //有参数结构体构造函数
	  N[4] = { 5,"python3",'p' };

	//现在我们开始打印观察是否已经存入
	for (int i = 0; i < 5; i++){
		cout << N[i].data << " " << N[i].str << " " << N[i].x << endl;
	}
	system("pause");
	return 0;
}

输出结果

1 hello c
2 c++ d
3 java e
4 python f
5 python3 p
posted @ 2020-10-28 00:18  解尼  阅读(608)  评论(0编辑  收藏  举报