- 结构体/构造函数例程
这是我在网上看的,一个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。
- 例程 算法竞赛入门经典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型结构体。