一、对象内存
内存对齐:与结构体的内存对齐相同
函数不占用对象的内存
static不占用对象的内存大小,static属于类
class student{
public:
void setAge( int a ){ age = a; }
int getAge()const {return age;}
private:
char name[20];
short age;
int score;
char sex;
}
二、拷贝构造
是一个构造函数,拷贝别人的,创建自己的构造函数
默认函数:无参构造、析构、拷贝构造。
当自己没有编写以上函数时,系统会默认实现以上函数
class student{
public:
student( char *str,int a){
strcpy( name , str );
this->age = a;
}
//拷贝构造
student( const student %rhs ){
memcpy( this , &rhs ,sizeof(rhs) );
}
void show()const{ cout << this->name << "," << age <<endl; }
private:
char name[20];
short age;
}
int main()
{
student tom("tom",18);
student lucy( tom );
return 0;
}
三、this指针
定义:谁调用指向谁
四、拷贝
浅拷贝/位拷贝:
当类里面有指针时,浅拷贝可能会导致“牵一发而动全身”(当有其中任一一个字符串改变,会导致所有指向该字符串的内容都改变)。
浅拷贝只是对指针进行复制,复制完成后,两个指针指向同一个内存空间,所以会“牵一发动全身”
class student{
public:
student( char *str,int a){
name = str ;
this->age = a;
}
//拷贝构造
student( const student %rhs ){
//memcpy( this , &rhs ,sizeof(rhs) );
this->name = rhs.name;
this->age = rhs.age;
}
void show()const{ cout << this->name << "," << age <<endl; }
private:
char *name;
short age;
}
int main()
{
char str[] = {"tom"};
student tom( str ,18);
student lucy( tom );
str[0] = 'T';
tom.show();
lucy.show();
return 0;
}
深拷贝
拷贝的是指针和指针所指向的内容,拷贝后,两个指针指向不同地址的内存空间,但内容相同。需要在拷贝前考虑是否需要给指针分配大小内存空间。
class student{
public:
student( char *str,int a){
name = new char[10];
strcpy(name,str);
this->age = a;
}
//拷贝构造
student( const student &rhs ){
name = new char[10];
memcpy( this , &rhs ,sizeof(rhs) );
}
void show()const{ cout << this->name << "," << age <<endl; }
private:
char *name;
short age;
};
int main()
{
char str[] = {"tom"};
student tom( str ,18);
student lucy( tom );
str[0] = 'T';
tom.show();
lucy.show();
return 0;
}