C++面向对象程序设计——类作用域

//类作用域
//


#include <iostream>
#include <string>
using namespace std;

void doA(){
    int a;
    a = 12;
}

void doB(){
    int b;
    b = 99;
}

class First{
public:
    int memi;
    double memd;
    void doC(){
        memi = 22;
    }
};
int height;//全局作用域的变量

class ScreenB{
public:
    typedef std::string::size_type index;
    void dummy_fun(index height){ //函数作用域的height
        //cursor = width * height; //这是哪个height?是函数作用域中参数的height
        //cursor = width * this->height;  //此时的height是类的数据成员height
        cursor = width * ::height; //此时的height是全局变量的height,四个点::是代表全局作用域的变量
    }
private:
    index cursor;
    index height, width; //类作用域
};
class ScreenA{
public:
    typedef std::string::size_type index;
    char get(index r, index c) const{
        index row = r * width;
        return contents[row + c];
    }
    index get_cursor() const;
private:
    std::string contents;
    index cursor;
    index height, width;
};

ScreenA::index ScreenA::get_cursor() const{ //index前必须明确写出类作用域
    return cursor;
}

int main(){
    //index ht; //不可以使用
    ScreenA::index ht; //加了类作用域

    ScreenA sa;
    ScreenB b;

    //a = 8; //此处a离开了doA的作用域,
    doA();
    doB();
    //doC();//doC的作用域位于类的内部

    First obj;

    //要调用doC()
    obj.doC();
    First *ptr = &obj;  //使用指针调用doC()
    obj.memi = 12; //通过对象使用数据
    //memi = 12 //此处不可以,离开了class First的作用域
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值