【C++】struct结构体/构造函数

  1. 结构体/构造函数例程
    这是我在网上看的,一个struct中的变量的初始化方式有以下好几种:
#include <iostream>
#include <string>
#include <stdlib.h>
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(65), str("asd"), data(5){} //char为A,str为asd,数据为5
	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");
}

在赋值的过程中,输入有参/无参会调用不同的函数进行初始化,所以数值是不一样的。
this是指向当前对象的指针,this->x是当前对象的成员变量x。

  1. 例程 算法竞赛入门经典p105
#include <iostream>
#include <stdlib.h>
using namespace std;

struct Point{
    int x,y;
    Point(int x=0, int y=0):x(x),y(y){}
};

Point operator + (const Point &A, const Point &B){
    return Point(A.x+B.x, A.y+B.y);
}

ostream & operator << (ostream &out, const Point &p){
    out << "("<<p.x<<","<<p.y<<")";
    return out;
}

int main(){
    Point a,b(1,2);
    a.x = 3;
    cout << a+b << endl;
    system("pause");
}

这段代码定义了【为这个结构体专有的】运算符+,可以对于这个结构体实行”加法“。
同样定义了【为这个结构体专有的】流输出方式,可以用cout<<p来输出一个Point型结构体。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值