文章概述
- const修饰普通成员函数
- 全局函数和成员函数
const修饰普通成员函数
我们知道this指针指向的是具体的对象,普通的成员函数存在(加深记忆),设计this指针的时候格式为*const this(常量指针)。我们看下面的代码:
//对于这个普通的成员函数const其实放在下面的这3个地方都没有关系的
//但是一般放在(3)
(1)void (2)func(int x)(3)
{
}
我们想一想const修饰的谁? 我们做一个完整的案例:
class Test
{
int a;
int b;
public :
Test()
{
a = 10;
b = 8;
}
//我们知道const修饰的变量值不能发生改变
void func(int x, int y)const
{
//x的值可以改变,所以1假设不成立
x = 10;
//y的值可以改变,所以2假设不成立
y = 8;
//我们发现a的值不能改变,得出const修饰的是this
//this->a = 10;
}
};
int main()
{
//1.我们假设修饰的是形参x
//2.我们假设修饰的是形参y
//3.我们假设修饰的是成员变量a
return 0;
}
我们得出const修饰普成员函数时,修饰的是this指针(this指针指向的内存空间的值不会发生变化)。
//对于这个函数,其实可以变成const Test *const this;
void func(int x, int y)const;
全局函数和成员函数
通过一个案例可以知道两者如何转化的:
class Test
{
int a;
public :
Test(int x)
{
this->a = x;
}
int getA() { return a; }
Test Gets(Test& b)
{
Test temp(this->a + b.getA());
return temp;
}
};
//全局函数实现对象相加
Test Get(Test& a,Test& b)
{
Test temp(a.getA() + b.getA());
return temp;
}
int main()
{
Test a(8);
Test b(2);
//全局函数
Test c = Get(a,b);
//成员函数
Test d = a.Gets(b);
cout << c.getA() << endl;
cout << d.getA() << endl;
return 0;
}
总结:
a. 全局函数转化成员函数时,通过this指针隐藏左操作数;
b. 成员函数转化为全局函数时,多了一个参数。
我们有时候会困扰什么时候返回引用什么时候返回对象???
class Test
{
int a;
public :
Test(int x)
{
this->a = x;
}
int getA() { return a; }
Test Gets(Test& b)
{
Test temp(this->a + b.getA());
return temp;
}
Test& Getd(Test& b)
{
this->a = this->a + b.getA();
return *this;
}
};
观察Gets函数和Getd函数,其实对于临时对象不要返回引用,记住这点就可以了。