变量作用域与this指针

来源:互联网 发布:捕鱼软件破解 编辑:程序博客网 时间:2024/06/11 04:53

对于this的看法(引自wrean):this 本身在英语中不就是简化语言的作用么。比如如果楼上问我 “这门课是老崔老师教的吗?”
我可以有两种回答方式:“是老崔老师(radius_)”或者“就是这个老师(*this)”


【对于C语言来说】
【Global variables(全局变量)】
are declared outside all functions and are accessible in its scope.(在所有函数外面声明并在其作用域内可以被所有函数访问)
The scope starts from its declaration and continues to the end of the program.(作用域起于声明,止于程序结束)

【Local variables(局部变量)】
are defined inside functions.(在函数内定义)
The scope starts from its declaration and continues to the end of the block that contains the variable(作用域起于声明,止于包含该变量的块尾)

【Static local variables(静态局部变量)】
permanently stored in the program
can be used in the next call of the function

【The Scope of Data Fields in Class(类中数据域的作用域)】
The data fields
- are declared as variables inside class(被定义为变量形式)
- are accessible to all constructors and functions in the class(可被类内所有函数访问)
Data fields and functions can be declared in any order in a class(数据域和函数可以以任意顺序声明)

【代码a】

class Circle{public:    Circle();  //构造函数名和类的名字是一样的,注意大小写    Circle(double);    double getArea();    double getRadius();    void setRadius(double);private:    double radius;};

【代码b】

class Circle{public:    Circle();    Circle(double);private:    double radius;public:    double getArea();    double geatRadius();    void setRadius(double);};

【代码c】

class Circle{private:    double radius;public:    double getArea();    double getRadius();    void setRadius(double);public:    Circle();    Circle(double);}

以上三个 数据域和函数 就是以任意顺序声明的,都是正确的

【Hidden by same name(同名屏蔽)】
If a local variable has the same name as a data field;(若成员函数中的局部变量与某数据域同名)

  • the local variable takes precedence(局部变量优先级高)
  • the data field with the same name is hidden (同名数据域在函数中被屏蔽)
    example:
#include <iostream>using namespace std;class Foo{public:    int x;   // data field    int y;   // data field    Foo(){        x = 10;        y = 10;    }    void p()    {        int x = 20;   //local variable (覆盖掉了data field的x)        cout << "x is " << x << endl;        cout << "y is " << y << endl;    }};int main(){    Foo foo;    foo.p();   //输出 x is 20  y is 10    return 0;}

【The this Pointer】
How do you reference a class’s hidden data field in a function?(如何在函数内访问类中被屏蔽的数据域)

this keyword

  • a special built-in pointer(特殊的内建指针)
  • references to the calling object.(引用当前函数的调用对象)
    例:
class Circle{public:    Circle();    Circle(double radius){//这个是局部变量        this->radius = radius;           //this->radius指的是类的数据域,radius指的是局部变量    }private:    double radius;public:    void setRadius(double);    //....};

例:当Screen类中有两个函数move( )和set( ),如何设计这两个函数的返回值,才能使得
myScreen.move(4,0).set('#'); 是合法的?
set(‘#’)表明myScreen.move(4,0)返回的是一个对象,所以返回类型为 *this

0 0
原创粉丝点击