类的作用域
每个类都会定义自己的作用域。
Screen::pos ht=24,wd=80; //使用Screen定义的pos类型
Screen scr(ht, wd, ' ');
Screen *p=&scr;
char c=scr.get(); //访问scr对象的get成员
c=p->get(); //访问p所指对象的get成员
作用域和定义在类外部的成员
一个类就是一个作用域,但是要定义函数的时候,要在类的外部定义,那么就要明确告诉编译器那个类的函数是该类的。
void Window_mgr::clear(ScreenIndex i)
{
//s是一个Screen的引用,指向我们想清空的那个屏幕
Screen &s=screens[i];
//将那个选定的Screen重置为空白
s.contents=string(s.height*s.width, ' ');
}
class Window_mgr
{
public:
//窗口中每个屏幕的编号
using ScreenIndex=std::vector<Screen>::size_type;
//按编号将指定的Screen重置为空白
void clear(ScreenIndex);
//向窗口添加一个Screen,返回他的编号
ScreenIndex addScreen(const Scrren&);
private:
//这个Window_mgr追踪的Screen
//默认情况下,一个Window_mgr包含一个标准尺寸的空白Screen
std::vector<Screen> screens{Screen(24, 80, ' ')};
};
其中函数
ScreenIndex addScreen(const Scrren&);
的实现:
//首先处理返回类型,之后我们才进入Window_mgr的作用域
Window_mgr::ScreenIndex
Window_mgr::addScreen(const Screen &s)
{
screens.push_back(s);
return screens.size()-1;
}
由于ScreenIndex在类的外面是不存在的类型,所以要想在外面用这个类型那么就得在前面声明是Window_mgr类里面的类型。
题目7.33
这样改!!!
class Screen
{
public:
//....
pos size() const;
//其他不变
};
然后外面定义的时候
Screen::pos
Screen::size() const
{
return height*width;
}
名字查找与类的作用域
typedef double Money;
string bal;
class Account
{
public:
Money balance() {return bal;} //这个bal是private里面的bal
private:
Money bal;
//...
};
类型名要特殊处理
typedef double Money;
string bal;
class Account
{
public:
Money balance() {return bal;} //这个bal是private里面的bal
private:
typedef double Money; //错误:不能重新定义Money
Money bal;
//...
};
题目7.35
typedef string Type;
Type initVal();
class Exercise
{
public:
typedef double Type;
Type setVal(Type);
Type initVal();
private:
double val;
};
Type Exercise::setVal(Type parm) //这里加了个Exercise::
{
val=parm+initVal();
return val;
}
修改后:
typedef string Type;
Type initVal();
class Exercise
{
public:
typedef double Type;
Type setVal(Type);
Type initVal();
private:
double val;
};
//修改部分一下
Exercise::Type Exercise::initVal()
{
}
//以上
Exercise::Type Exercise::setVal(Type parm) //这里加了个Exercise::
{
val=parm+initVal();
return val;
}
PS:不知道现在自己做的对不对,好不好,但是要坚持下去,以后的事情哪有那么多的时间去想,老想以后还不如把现在当前手上的事情做好,免得以后又后悔现在没有做好,(╯‵□′)╯︵┻━┻,努力奋斗!!!什么都不想,就是做好当前的每一件事!!!