类、结构体、指针

yxy123456 / 2024-10-23 / 原文

1、类的定义

class Person
{
	private:
		int age,height;
		double money;
		string books[100];
	public:
		string name;
		
		void say()
		{
			cout<<"I'm"<<name;
		}
		int get_age()
		{
			return age;
		}
		void add_money(double x)
		{
			money+=x;
		}
}

类中的变量和函数被统一称为类的成员变量。

private后面的内容是私有成员变量,在类的外部不能访问;public后面的内容是公有成员变量,在类的外部可以访问。

类的使用:

#include <iostream>

using namespace std;

const int N = 1000010;

class Person
{
	private:
		int age,height;
		double money;
		string books[100];
	public:
		string name;
		
		void say()
		{
			cout<<"I'm"<<name<<" ";
		}
		int set_age(int a)
		{
			age = a;
		}
		
		int get_age()
		{
			return age;
		}
		
		void add_money(double x)
		{
			money += x;
		}
} Person_a,person_b,persons[100];

int main()
{
	Person c;
	
	c.name = "yxc";
	c.age = 18;
	c.set_age(18);
	c.add_money(100);
	
	c.say();
	cout<<c.get_age()<<endl;
	
	return 0;
}

结构体和类的作用是一样的。不同点在于类默认是private,结构体默认是public。

struct Person
{
	private:
		int age,height;
		double money;
		string books[100];
		
	public:
		string name;
		
		void say()
		{
			cout<<"I'm"<<" ";
		}
		
		int set_age(int a)
		{
			age = a;
		}
		
		int get_age()
		{
			return age;
		}
		
		void add_money(double x)
		{
			money += x;
		}
}Person_a,person_b,Persons[100];

2、指针和引用

指针指向存放变量的值的地址。因此我们可以通过指针来修改变量的值。

#include <iostream>

using namespace std;

int main()
{
	int a=10;
	int *p = &a;
	
	*p += 5;
	cout<<a<<endl;
	
	return 0;
}

数组名是一种特殊的指针。指针可以做运算:

#include <iostream>

using namespace std;

int main()
{
	int a[5] = {1, 2, 3, 4, 5};
	
	for(int i = 0;i < 5;i ++)
		cout<<*(a+i)<<endl;
		
	return 0;
}

引用和指针相似,相当于给变量起了个别名。

#includ <iostream>

using namespace std;

int main()
{
	int a = 10;
	int &p = a;
	
	p += 5;
	cout << a << endl;
	
	return 0;
}

3、链表

#include <bits/stdc++.h>

using namespace std;
struct Node
{
	int val;
	Node*next;
	
	
	
};
void sc(Node*head)
{
	if(nullptr==head->next)
	{
		return;
	}
	while(head!=nullptr)
	{
		cout<<head->val<<" ";
		head=head->next;
	}
}
int main()
{
	Node*n0= new Node;
	Node*n1= new Node; 
	Node*n2= new Node;
	
	n0->val=0;
	n1->val=1;
	n2->val=2;
	
	n0->next=n1;
	n1->next=n2;
	n2->next=nullptr;
	
	sc(n0); 
	return 0;
}