1.C++三大特征: 封装 继承 多态
1.public: 任意位置访问
2.protected: 本类,子类类中访问
3.private: 本类类中访问
2.struct class
3.this (thiscall)
类中普通的成员方法中有默认的参数 this
this Student*const
普通成员方法依赖对象调用
4.成员方法在类外实现
1.类中 inline
2.类外 普通
5.类中6个默认的函数
1.公有的
2.inline
1.构造函数
初始化对象的内存空间
1.可以重载
2.不能手动调用
3.顺序构造
class Student{
private:
char *m_name;
int m_age;
float m_score;
public:
//声明构造函数
Student(char *name, int age, float score);
//声明普通成员函数
void show();
};
//定义构造函数
Student::Student(char *name, int age, float score){
m_name = name;
m_age = age;
m_score = score;
}
//定义普通成员函数
void Student::show(){
cout<<m_name<<"的年龄是"<<m_age<<",成绩是"<<m_score<<endl;
}
int main(){
//创建对象时向构造函数传参
Student stu("Li", 15, 92.5f);
stu.show();
//创建对象时向构造函数传参
Student *pstu = new Student("Hua", 16, 96);
pstu -> show();
return 0;
}
2.析构函数
释放其他资源
1.不可重载
2.可以手动调用 ==》 退化成普通函数的调用
3.先构造的后析构
class Func{
public:
Func(int len); //构造函数
~Func(); //析构函数
public:
void input(); //从控制台输入数组元素
void show(); //显示数组元素
private:
int *at(int i); //获取第i个元素的指针
private:
const int m_len; //数组长度
int *m_arr; //数组指针
int *m_p; //指向数组第i个元素的指针
};
Func::Func(int len): m_len(len){
if(len > 0){ m_arr = new int[len]; /*分配内存*/ }
else{ m_arr = NULL; }
}
Func::~Func(){
delete[] m_arr; //释放内存
}
void Func::input(){
for(int i=0; m_p=at(i); i++){ cin>>*at(i); }
}
void Func::show(){
for(int i=0; m_p=at(i); i++){
if(i == m_len - 1){ cout<<*at(i)<<endl; }
else{ cout<<*at(i)<<", "; }
}
}
int * Func::at(int i){
if(!m_arr || i<0 || i>=m_len){ return NULL; }
else{ return m_arr + i; }
}
int main(){
//创建一个有n个元素的数组(对象)
int n;
cout<<"Input array length: ";
cin>>n;
Func *parr = new Func(n);
//输入数组元素
cout<<"Input "<<n<<" numbers: ";
parr -> input();
//输出数组元素
cout<<"Elements: ";
parr -> show();
//删除数组(对象)
delete parr;
return 0;
}
3.拷贝构造函数 浅拷贝
用已存在的对象来生成一个相同类型的新对象
1.形参用&接收 防止递归构造形参对象导致栈溢出
4.赋值运算符的重载函数
5.取地址操作符的重载函数
6.const修饰的取地址操作符的重载函数
对象的生成
1.开辟内存
2.内存空间进行初始化 调用构造函数
对象的销毁
1.释放其他资源 调用析构函数
2.释放空间