返回

C++_new和delete、静态成员、this指针、全局函数成员函数友元函数

发布时间:2022-11-11 11:52:05 281
# 数据

对象内存空间的动态建立和释放
new和delete操作符相当于C中的malloc和free
new可以应用的类型:基础类型变量、数组变量、类对象

基础类型变量
int main(){
int *p1=(int *)malloc(sizeof(int));
*p1=10;
free(p1);

int *p2=new int;
*p2=20;
delete p2;

int *p3=new int(30);
delete p3;
}


数组类型变量
int main(){
int *p1=(int *)malloc(sizeof(int)*10);
p1[0]=10;
free(p1);

int *p2=new int[10];
p2[0]=20;
delete []p2;
}


分配对象
new可以执行类的构造函数,delete可以执行类的析构函数。但是malloc和free不行
class test{
public:
test(int var){
a=var;
}
private:
int a;
};
int main(){
test *p1=(test *)malloc(sizeof(test));
free(p1);

test *p2=new test(10);
delete p2;
}

静态成员变量和函数
把一个类的成员定义为static时,这个类无论有多少个对象,这些对象共享这个static成员

class test{
public:
static void getc(){ 静态成员函数
cout<<c<<endl;
} 在静态成员函数中,不可以调用普通的成员属性或普通函数
private:
int a;
int b;
static int c;
};
int test::c=10;

int main(){
test t;
t.getc(); 正确
test::getc(); 正确
}

C++中的成员函数和成员变量时分开存储的
成员变量
普通成员变量:存储在对象中
静态成员变量:存储在可读写数据区

成员函数:都存在代码区
普通成员函数:隐藏包含一个指向当前对象的this指针

定义一个类的对象,其在栈区所占内存是普通成员变量所占内存的总和

this指针

class test{
public:
test(int var_a, int var_b){ -->test(test* const this, int var_a, int var_b)
a=var_a; -->this->a=var_a
b=var_b; -->this->b=var_b
}
private:
int a;
int b;
};
int main(){
test t(1, 2);
}

const
类中的成员函数用const修饰,const的位置可在任意位置
const修饰的是this指针所指向的内存空间,不可被修改。
因为this指针被隐藏掉,所以一般const放在函数的后面函数体的前面

全局函数和成员函数的相互转化

class test{
public:
int a;
int b;
public:
test(int a=0, int b=0){
this->a=a;
this->b=b;
}
test test_add(test &t){
test tmp(this->a+t.a, this->b+t.b);
return tmp;
}
};
test add_test(test &t1, test &t2){
test tmp(t1.a+t2.a, t1.b+t2.b);
return tmp;
}
int main(){
test t1(1, 2);
test t2(3, 4);

test t3=t1.test_add(t2); 匿名对象转化为实体

test t4;
t4=t1.test_add(t2); 匿名对象析构

test t5;
t5=add_test(t1, t2);
}

返回对象本身的成员函数

class test{
public:
int a;
int b;
public:
test(int a=0, int b=0){
this->a=a;
this->b=b;
}
test test_add(test &t){
test tmp(this->a+t.a, this->b+t.b);
return tmp;
}

返回一个引用,相当于返回自身
test& add(test &t){
this->a=this->a+t.a;
this->b=this->b+t.b;
return *this;
}
};
int main(){
test t1(1, 2);
test t2(3, 4);
t1.add(t2);
虽然返回自身是返回一个元素,但是在函数内部是修改他t1自身,不用再用t1接
}

友元函数

class test{
public:
friend void change(test *tp, int var);
test(int a, int b){
this->a=a;
this->b=b;
}
private:
int a;
int b;
};
void change(test *tp, int var){
tp->a=var;
}
int main(){
test t(1, 2);
change(&t, 100);
}

友元类
若B类是A类的友元类,则B类的所有成员函数都是A类的友元函数
友元类通常设计为一种对数据操作或类之间传递消息的辅助类

class A{
public:
friend class B;
B是A的友元类,在B中可以访问和修改A中的私有成员和函数
A(int a=0, int b=0){
this->a=a;
this->b=b;
}
private:
int a;
int b;
};
class B{
public:
void setA(int var){
obj.a=var;
}
private:
A obj;
};


特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
求二进制数中 1 的个数 2022-11-11 11:26:24