封装总结:
staic ->类属性和类方法,这样就与类进行了绑定了 没有this指针,跟着类走的 static int s_count; int People:😒_count=123;//此时才分配内存空间 私有化构造函数,设置静态函数来调用构造方法 :安全,降低内存管理的难度(创建时可以放入一个内存池进行管理)
class Mysort{
static void sortInsert(){
cout<<"1223"<<endl;
}
static void sortQuick(){
cout<<"1223"<<endl;
}
static void sortInsert(){
cout<<"1223"<<endl;
}
static void sortSelect(){
cout<<"1223"<<endl;
}
}
const 修饰类成员属性,成员方法,修饰静态成员,修饰成员函数, string &getName{}const 不能对类this对象修改
void addAge()const{
this->age=18
}
声明为mutable int age后可进行修改
int*p=(int*)&(this->age);
*p=123;
const 不能修饰static方法 const 可以在声明时直接对变量初始化
const static int count =0;//全局常量 可以在const 方法修改staic
A a=1;//1->A//这里会出现隐士转换 A b(1);A c(1.0);//这里会出现类型转换 //这里可以在构造函数 A(int n): _n(n){}前面加上explicit(显嗲式调用) 取消隐式转换
RVO(返回值优化):
C++的一种编译优化技术: 可以省略函数返回过程中复制构造函数的多余调用 解决“C++中临时对象的效率问题”
Class A{
private :
int _n;
public:
A(){
cout<<"default constructor"<<endl;
};
A(int n) :_n(n){
cout<<"int constructor! address ="<<this<<endl;
}
A(const A&a){
cout<<"copy constructor address ="<<this<<endl;
}
~A(){
cout<<"desctructor! address ="<<this<<endl;
}
void operator =(const A&a){
cout<<"operator=!!"<<endl;
}
};
A func(){
A temp(123);
return temp;
}
int main(){
A a=func();
return 0;
}
Class A{
private :
int _n;
public:
A(){
cout<<"default constructor"<<endl;
};
A(int n) :_n(n){
cout<<"int constructor! address ="<<this<<endl;
}
A(const A&a){
cout<<"copy constructor address ="<<this<<endl;
}
~A(){
cout<<"desctructor! address ="<<this<<endl;
}
void operator =(const A&a){
cout<<"operator=!!"<<endl;
}
};
class B{
private:
A da;
A*pA;
public:
B(A*a):da(*a),pA(new A(*a)){
cout<<"B copy constructor111"<<endl;
}
B(A a){
cout<<"B copy constructor222"<<endl;
this->da=a;
this->pA=new A(a);
}
};
A func(){
A temp(123);
return temp;
}
int main(){
A a;
B b=&a;
cout<<"======="<<endl;
B c=a;
cout<<"======="<<endl;
return 0;
}
内存泄漏检测:
#ifndef _MEMCHECK_H_
#define _MEMCHECK_H_
#include <iostream>
void* operator new(size_t size, const char* file, unsigned long line);
void* operator new[](size_t size, const char* file, unsigned long line);
void operator delete(void* ptr);
void operator delete[](void* ptr);
#ifndef _NEW_OVERLOAD_IMPLEMENTATION_
#define new new(__FILE__, __LINE__)
#endif
class MemCheck{
public:
~MemCheck();
static void setMemInfo(void* p, const char* file, unsigned long line,
unsigned long size);
static void deleteMemInfo(void* p);
};
#endif
#define _NEW_OVERLOAD_IMPLEMENTATION_
#include "memcheck.h"
void* operator new(size_t size, const char* file, unsigned long line){
if(size == 0)
size = 1;
void* ptr = malloc(size);
if(ptr == nullptr)
std::cout << "ERROR NEW " << std::endl;
return ptr;
}
void operator delete(void* ptr){
if(ptr) free(ptr);
}
#include<iostream>
#incclude "memcheck.h"
using namespace std;
class A{};
int main(){
A*p=new A();
cout<<sizeof(A)<<endl;
return 0;
}
|