C++学习之路抓紧跑路版(八)-类(一)

本文介绍了C++中的类与对象基础知识,包括如何定义类、创建对象及使用对象的方法。通过示例展示了如何初始化类的成员、创建二维数组、实现栈的功能以及在堆空间创建对象。强调了栈空间与堆空间对象调用方法的区别。


前言

我们从这一节开始就开始学习C++的一大特色“类”了,可能内容会比较多,我们开始吧!加油


一、定义一个类

1、定义类
class 类名{
类成员属性:public、private、protected
};
2、创建类对象
类名 对象名;
3、使用类对象的成员
对象名.方法;

我们来举一个简单的例子吧:

#include<iostream>
using namespace std;
class student{
public:
        void fun()
        {
                cout<<"test test test"<<endl;
        }
};
int main()
{
        student lishuo;
        lishuo.fun();
}

输出:

test test test

示例2:

#include<iostream>
#include<string>
using namespace std;
class student{
public:
        string name;
        int age;
        void setname(string n)
        {
                name = n;
        }
        void setage(int a)
        {
                age = a;
        }
        void fun()
        {
                cout<<name<<endl;
                cout<<age<<endl;
        }
};
int main()
{
        student lishuo;
        lishuo.setname("lishuo");
        lishuo.setage(18);
        lishuo.fun();
}

示例3,利用类输入特定样式的特定二维数组:

#include<iostream>
#include<string>
using namespace std;
class student{
public:
	int arr[3][4];
	void init()
	{
		for(int i = 0;i < 3;i++)
		{
			for(int j = 0;j < 4;j++)
			{
				arr[i][j] = i+j;
				cout<<arr[i][j];
			}
			cout<<endl;
		}
	}
	void init1(char space)
	{
		for(int i = 0;i < 3;i++)
		{
			for(int j = 0;j < 4;j++)
			{
				arr[i][j] = i + j;
				if(j < 3)
				{
					cout<<arr[i][j]<<space;
				}
				else
				{
					cout<<arr[i][j];
				}
			}
			cout<<endl;
		}
	}
};
int main()
{
	student lishuo;
	lishuo.init();
	lishuo.init1('#');
}

输出:

0123
1234
2345
0#1#2#3
1#2#3#4
2#3#4#5

示例4,尝试创建一个栈,指针p指向栈stack,有入栈push()出栈pop()函数,不断填入整形数据,其中如果数据到达临近值则调用成员expand()方法进行扩容,index表示栈针:

#include<iostream>
using namespace std;
class stack{
public:
	int *p;
	int length;
	int index = 0;
	void init()
	{
		length = 10;
		p = new int[length];
	}
	void push(int num){
		if(length == index)
		{
			expand();
		}
		p[index] = num;
		index++;

	}
	int pop()
	{
		index--;
		return p[index];
	}
	void expand(){
		int newlength = length * 2;
		int *newstack = new int[newlength];
		for(int i = 0;i < length;i++)
		{
			newstack[i] = p[i];
		}
		p = newstack;
		delete p;
		length = newlength;

	}
};
int main()
{
	stack lishuo;
	lishuo.init();
	for(int i = 0;i < 30;i++)
	{
		lishuo.push(i);
	}
	for(int i = 0;i < 10;i++)
	{
		cout<<lishuo.pop()<<endl;
	}
}

输出:

29
28
27
26
25
24
23
22
21
20

二、堆空间创建类对象

我们在创建对象的时候不仅可以在栈空间创建对象,而且可以利用new在堆空间上创建类对象,我们来开一下示例(这里直接用上一个例子):

int main()
{
        student *lishuo = new student;
        lishuo->init();
        lishuo->init1('#');
        delete lishuo;
}

我们需要注意的是在栈空间创建的对象,所以可以用 . 来调用方法,但如果用堆空间来创建对象的话那么就需要用“->”来调用方法了。

总结

第一部分关于类的内容就先介绍到这里吧,下一节继续讲解类的其他用法,我们好好学(pao)习(lu)吧!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值