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();
}
谢谢大家的阅读,新手上路,如有不足之处请及时指出,我好纠正,万分感激~