C++ 类——const修饰普通成员函数,通常放在最后面

目录:
一、经典问题:C++ 类中,const修饰普通成员函数时修饰的是谁?
二、const修饰普通成员函数
三、全局函数和成员函数

一、经典问题:C++ 类中,const修饰普通成员函数时修饰的是谁?

  1. 函数的后面放const的情况 ,不能说是const修饰函数,因为const修饰的是谁,需要研究分析
    本节学习:在一个类中,类的成员函数void OpVar( int a, int b) const (推荐这样写)
    它的等价写法有:const void OpVar( int a, int b) 或void const OpVar( int a, int b)
  2. 类中的成员函数写成 void OpVar( int a, int b) const时,那么const修饰的是谁?
    结论:const修饰的是this指针(在*的左边),使this指针变成常量指针,常量指针是不能够通过指针修改指向的值。
    void OpVar( const Test *const this, int a, int b) 第二个const本来就有。
    (2)类成员函数void OpVar( int a, int b) 对应 void OpVar(Test *const this, int a, int b)
    (3)void OpVar( int a, int b) const 对应 void OpVar(const Test *const this, int a, int b)

二、const修饰普通成员函数(目的就是增强程序的健壮性)

const修饰普通成员函数
我们知道this指针指向的是具体的对象,普通的成员函数存在(加深记忆),编译器设计this指针的时候格式为*const this(指针常量)。我们看下面的代码:

//对于这个普通的成员函数const其实放在下面的这3个地方都没有关系的
//但是一般放在(3)
(1)void (2)func(int x)(3)
{
}
最常见的是:

 void  func (int  x)const
{
} 

我们想一想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指针指向的内存空间的值不会发生变化),即作用是:使this指针变成常量指针(指向常量的指针)。
实现的效果:不能够通过this指针来修改类的对象的成员变量的值,增加了程序的健壮性。

三、全局函数和成员函数

通过一个案例可以知道两者如何转化的:

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函数,其实对于临时对象不要返回引用,记住这点就可以了。

你可能感兴趣的:(02C/C++语言基础知识)