代码详解c++类作用域

/*

代码详解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=12;
        }
        void doD()
        {
            doC();//  doC()这个函数如果放在class First 这个类之外是错误的,因为那样的话就不在作用域之内
        }
 }; 
 
 class ScreenA
 {
     public:
         typedef std::string::size_type index; 
         
         char get(index r, index c)const; //const表示这是个常量函数即这个函数不会对里面的参数进行修改,只是做引用
         index get_cursor()const;
        
     private:
        std::string contents;
        index cursor;
        index height ,width;    
 };
 
 int height; //全局作用域 

 class ScreenB
 {
     public:
         typedef std::string::size_type index;
         void dummy_fcn(index height)
         {
             //cursor=width*height;//这个height是 void dummy_fcn()里面的height 
             //cursor=width*this->height; 这个height 是 ScreenB里面 private 里面的height

             cursor= width*::height;//这个height 是 int  的height,单独::表示的是全局的作用域 
              
         }
    private:
        index cursor;
        index height,width;
     
  }; 
 
 /*

index ScreenA::get_cursor()const   是错误写法。 因为在ScreenA之前,不知道index 是哪个作用域的 
 {
     return cursor;
 }

*/
 ScreenA::index ScreenA::get_cursor()const  //正确写法
 {
     return cursor;
  } 
char ScreenA:: get(index r, index c)const//当函数的定义写在类外面的时候,必须写上作用域  ScreenA:: 
         {
             index row= r*width;
             return contents[row+c];
          } 

int main()
{
    ScreenA::index ht;//错误写法是  index ht,因为index不在作用域内 
    ScreenA  sa; 
    ScreenB  sb;
    
    First obj;
    obj.memi=2;//通过定义对象,可以使用该作用域里面的 
    
    First *ptr=&obj;//指针的使用   通过指针可以使用作用域里的 
    ptr->doC();
    ptr->memi=99;
    
    doA();
    doB();
    

    return 0;
 } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值