/*类和对象
构造和析构 函数
构造函数的调用
构造函数分类:
(有参、(默认构造)无参)
普通、拷贝
封装
对象的特性
成员变量和成员函数分开存储
深拷贝:在堆区重新申请空间,进行拷贝操作
浅拷贝:简单的赋值拷贝操作
浅拷贝带来的问题:堆区内存重复释放。可以使用深拷贝来解决
初始化列表
类对象作为类成员(构造时先构造类对象,再构造自身,析构时,和构造顺序相反)
静态成员:
静态成员函数只能访问静态成员变量
不属于某一个对象的
*/
#include<iostream>
#include<string>
using namespace std;
class student{
public:
student(int a) {
}
int age;
};
class per {
public:
//构造函数
per() {
cout << "构造函数的调用" << endl;
}
per(int a) {
this->a = a;
cout << "有参构造" << endl;
}
per(int a, int * p) {
this->a = a;
this->p = p;
}
per(const per& p) {
cout << "拷贝构造" << endl;
//深拷贝
this->p = new int(*p.p);
}
//初始化列表
per(int a,int b,int c) :a(a),b(b),c(c) {//初始化列表
}
//析构函数
~per() {
//将堆区的数据释放干净
if (p != NULL) {
delete p;
p = NULL;
}
cout << "析构函数 的调用" << endl;
}
int a ;
int b ;
int c ;
static int d ;
int* p;
int getb() {
cout << b << endl;
return b;
}
static void staticfun(static int d) {
cout << d << endl;
cout << "static 函数调用" << endl;
}
private:
protected:
};//class per
int per::d = 10;
class stu : per {
};
bool same(per &p1, per &p2) {
if (p1.a == p2.a) {
return true;
}
else return false;
}
//调用
void test() {
per p1(11,22,33);
cout << p1.a << endl;
cout << p1.b << endl;
cout << p1.c << endl;
}
void test01() {
//通过对象调用静态函数
per p;
p.staticfun(1);
//通过类名访问
per::staticfun(1);
}
int main() {
//per p1;
//per p3;
//stu s1 ;
//
//
//test();
test01();
//p1.getb();
system("pause");
return 0;
}
夯实基础,学习笔记(cpp类和对象)
最新推荐文章于 2024-07-04 11:10:43 发布