/*
代码详解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;
}