C++中的类和对象

1类和对象的基本概念

1.1什么是类:一系列事物的抽象,万物皆可为类

类由两部分组成:属性 行为

属性:事物的特征——>数据类型描述

行为:事物的的操作

1.2 什么是对象:类的具体化,类的实例化

1.3类的特点:封装,继承(派生),多态

2类的定义

2.1创建语法

#include <iostream>
using namespace std;

class 类名1
{//权限限定词 public protected private等
public://共有属性
void printdata()//成员函数
{
cout << name << endl << age << endl;
}
protected://保护属性
string name;//数据成员
int age;
private://当前类不做继承处理,数据成员写成私有属性
};

 


2.2权限限定作用

类外只能访问public下的内容,习惯把public属性叫做类外的接口

类外只能通过对象访问类内的数据 struct成员除外

protected和private类外都不可访问,但可以提供共有接口间接访问

默认属性是私有属性,权限限定词只用来限定类外的访问,并不是限定中的访问(在类中可调用任意部分)

class 类名1
{//权限限定词 public protected private等
int hhhh;//默认属性,是私有属性
public://共有属性
void printdata()//成员函数
{
cout << namein << endl << agein << endl;
}
void initdata(string name,int age);//在类中创建函数
protected://保护属性
string namein;//数据成员
int agein;
private://当前类不做继承处理,数据成员写成私有属性
};

void 类名1::initdata(string name,int age)//在类外实现函数,注意::类名限定
{
namein = name;
agein = age;
}
int main()
{
//age = 18;//报错不可访问
类名1 A;
A.printdata();//可以访问public中的内容
//A.name;//报错不可访问,同样private中的内容也不可访问哦
A.initdata("嗨皮", 19);//间接访问namein agein
A.printdata();
return 0;
}

 


2.3C++结构体在一定程度上可以看作是类

struct student
{
int num;
protected:
int age;
private:
int score;
};
void teststruct()
{
student A = { 7,18,99 };//报错有不可访问的
A.num = 8;
A.age = 18;//报错不可访问
}

//但这样时

struct student
{
int num;
//protected:
int age;
//private:
int score;
};
void teststruct()
{
student A = { 7,18,99 };//不报错有可访问的
A.num = 8;
A.age = 18;//不报错可访问
}

 


3对象的创建

3.1分为:普通对象 对象数组 new一个对象

class 类名1
{//权限限定词 public protected private等
int hhhh;//默认属性,是私有属性
public://共有属性
void printdata()//成员函数
{
cout << namein << endl << agein << endl;
}
void initdata(string name,int age);//在类中创建函数
protected://保护属性
string namein;//数据成员
int agein = 18;//新标准可以在类中进行数据初始化
private://当前类不做继承处理,数据成员写成私有属性
};

int main()
{
//age = 18;//报错不可访问
类名1 A;//普通对象的创建
类名1 B[4];//数组对象的创建
for (int i = 0; i < 4; i++)//访问
{
B[i].initdata(string("name") + to_string(i), i + 18);
B[i].printdata();
}

类名1* p = new 类名1;//new一个
delete p;
p = nullptr;
return 0;
}

 


4成员的访问

4.1通过提供 公有接口进行数据访问

4.2通过提供 共有接口返回值进行数据访问

4.3默认值初始化

#include <iostream>
#include <string>
using namespace std;

class student
{
public:
void initdata(string name, int age)
{
namein = name;
agein = age;
}
void printdata()
{
cout << namein << endl << agein << endl;
}
string& getname()//返回引用
{
return namein;
}
int& getage()
{
return agein;
}
protected:
string namein = "hhh";//默认值初始化
int agein = 18;
//不做初始化将是一个垃圾值
};

int main()
{
//传参
student A;
A.initdata("hhh", 18);
A.printdata();

//返回引用
student B;
B.getname() = "hhh";
B.getage() = 18;
B.printdata();

//默认值初始化
student C;
C.printdata();
return 0;
}

 


好啦,就就就到这里啦。
————————————————
版权声明:本文为CSDN博主「#小狐狸」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_50208608/article/details/121392368

本文出自:https://blog.csdn.net/qq_50208608/article/details/121392368