一 概念
类:事物的抽象,万物皆可称为类,如车类、房类
类由两部分组成:属性和行为
属性:事物的特征,用数据类型来描述(类似C中变量)
string name; int age; double score;等等
行为:事物的操作、实现,用函数来描述,
void print() { }
int& getValue() {return age;}
对象:类的具体化,实例化
类的特点:封装、继承、多态
二 类的定义
创建语法
class 类名
{
//权限限定词
//公有属性
public:
void print()
{
cout<<m_name<<endl;
}
//保护属性
protected:
string m_name;
int m_score;
//私有属性 当前类不做继承处理,数据成员写成私有属性
private:
}; //此处有分号
类的定义一定放在全局区或命名空间内或类内。
权限限定词的作用:只用来限定类外访问,不限定类内访问
类外只能访问public属性内的东西
类外访问数据只能通过对象进行访问,static成员除外。
public:公有属性,类外可通过对象访问,通常在此处提供一些接口以实现类外访问类内的数据成员。
protected和private类外不可访问,但可以通过接口访问 ,这两者在继承中有区别
没有写在限定词下,默认为私有属性
C++ 结构体 在一定程序下可以直接当作类
默认属性为公有属性。
#include<iostream>
#include<string>
using namespace std;
class Student
{
int id; //没有写在限定词下,默认为私有属性
public:
void print()
{
cout <<"name:"<<name<<"\t" << "age:" << age << endl;
}
//为了在类外实现不能访问的部分,提供一些接口
//在类内声明,类外实现,当然也可以类内实现
void initData(string m_name, int m_age);
protected:
int age;
int score;
private:
string name;
};
void Student::initData(string m_name, int m_age)
{
name=m_name;
age = m_age;
}
int main()
{
Student s1;
//s1.score; // protected 类外不可访问
//s1.name; // private 类外不可访问
//s1.id; // 不可访问
s1.initData("小六",12); //那个对象调用函数,这个行为就属于那个对象的,
s1.print(); // public 类外可以访问
return 0;
}
三 对象创建
普通对象
对象数组
new一个对象
具体见代码段
#include <iostream>
#include <string>
using namespace std;
class Boy
{
public:
void print()
{
cout << name << "\t" << age << endl;
}
void initData(string Nname, int Nage)
{
name = Nname;
age = Nage;
}
protected:
//新标准,可以在类中给数据直接初始化
string name = "默认值";
int age =11;
};
int main()
{
//没有写构造函数的情况下,和C语言的创建方式是一样的
Boy boy;
boy.print(); //没有初始化数据
Boy boyArray[4]; //一般很少用对象数组
//mmArray[0]----mmArray[3]
//数组: 多个变量名有规律,内存连续的变量的集合
for (int i = 0; i < 4; i++)
{
//to_string 把数字转换为字符串
boyArray[i].initData(string("name")+to_string(i) , i + 19);
boyArray[i].print();
}
Boy* p = new Boy;
p->initData("法外狂徒张三", 18);
p->print();
delete p;
p = nullptr;
return 0;
}
四 成员访问(初始化)
通过提供 公有接口传参的方式初始化数据
通过提供 共有接口返回值 的方式(引用)初始化数据
默认初始化
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
//传参
void initData(string name, int age)
{
m_name = name;
m_age = age;
}
//返回引用
string& getName()
{
return m_name;
}
int& getAge()
{
return m_age;
}
void print()
{
cout << m_name << "\t" << m_age << endl;
}
protected:
//默认初始化
string m_name = "默认值";
int m_age = 0;
//不做初始化是一个垃圾值
};
int main()
{
Student xm;
xm.initData("小明", 19);
xm.print();
Student xl;
xl.getName() = "小李";
xl.getAge() = 18;
xl.print();
Student xz;
xz.print();
return 0;
}