C++知识梳理三C++类和对象

C++类和对象

类的定义

  • 什么是类,一系列事物的抽象,万物皆可为类
    • 类有两部分组成,属性和行为
      • 属性:事物的特征—>数据类型描述
      • 行为:事物的操作—>函数的描述
  • 类的特点,封装,继承/派生,多态…
  • C++类的定义,C++引入了新的关键字class,用来创建一个类,三个权限限定词public(共有属性),protected(保护属性),private(私有属性)
#include <iostream>
#include <string>
using namespace std;
class MM
{	//权限限定词
    public://共有属性
    void print(){//成员函数
	cout<<name<<"\t"<<age<<endl;
}
	void port(string _name,int _age);//声明成员函数

    protected://保护属性
    private://私有属性
    string name;
    int age;
};	

和结构体同样类外实现类中成员函数需要类名+权限限定词"::"

void MM::port(string _name,int _age){//定义成员函数
	_name=name;
	_age=age;
}

权限限定的作用

  • 类外只能访问public属性下面的 东西,习惯把 public属性叫做类外的接口,要想访问类中的数据,只能通过对象去访问(static成员除外)
  • protected属性和private属性下面的东西都不能类外访问,但是可以通过类外接口(public)间接访问
  • 默认属性(没有写在权限限定词下的属性)是 私有属性,不可访问
class GG{
	void print(){
	cout<<"私有属性,不可访问"<<endl;
	}
public:
protected:
private:
};

权限限定词只能用来限定对类外的访问,不能限定类内的访问,可以随意调用

  • C++结构体在一定程度上可以当做是一个类,只不过C++结构体的默认属性是public(共有属性)
struct MM 
{
	int num;   //默认属性是公有属性
protected:
	string name;
private:
	int age;
};

对象的定义

  • 什么是对象:类的实例化,类的具体化
    • 普通对象
    • 对象数组
    • new一个对象
      在没有写构造函数的情况下是和C语言的结构体创建方式是一样的
      普通对象
#include <iostream>
#include <string>
using namespace std;
class MM
{
    public://共有属性
    void print(){
	cout<<name<<"\t"<<age<<endl;
	}
	void initdata(string nname,int nage){//初始化对象
		nname=name;
		nage=age;
	}
    protected://保护属性
    private://私有属性
    string name;
    int age;
};
int main(){
	MM mm;//创建一个普通对象
	mm.print();
	return 0;
}

对象数组,一般情况下很少用对象数组

MM mm2[4];
for (int i = 0; i < 4; i++) 
	{
		mm2[i].initdata(string("name") + to_string(i), i + 19);
		mm2[i].print();
	}

new一个对象

MM* p = new MM;
	p->initdata("张三", 18);
	p->print();
	delete p;
	p = nullptr;

访问成员

  • 传参的方式访问成员
#include <iostream>
#include <string>
using namespace std;
class MM
{
public:
	void print()
	{
		cout << m_name << "\t" << m_age << endl;
	}
	void initData(string name, int age)
	{
		m_name = name;
		m_age = age;
	}

protected:
	string m_name;
	int m_age;
};
int main() {
	MM mm;
	mm.initData("小甜心", 19);
	mm.print();
	return 0;
}
  • 返回引用的方式访问成员
#include <iostream>
#include <string>
using namespace std;
class MM
{
public:
	void print()
	{
		cout << m_name << "\t" << m_age << endl;
	}
	string& getName()
	{
		return m_name;
	}
	int& getAge()
	{
		return m_age;
	}
protected:
	string m_name;
	int m_age;
};
int main() {
		MM mm2;
		mm2.getName() = "小可爱";
		mm2.getAge() = 18;
		mm2.print();
}

谢谢大家的阅读,新手上路,如有不足之处请及时指出,我好纠正,万分感激~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值