在定义于类外部的成员函数中,形参表和成员函数体都出现在成员名之后。这些都是在类作用域中定义,所以可以不用限定而引用其他成员。例如类Screen中的get的二形参版本的定义,该函数用Screen内定义的index类型来指定其参数类型。因为形参表在Screen类的作用域内,所以不必要指明我们想要的Screen::index。我们想要的是定义在当前类作用域中的,这是隐含的。同样,使用index、width、和contents时指的都是Screen类中声明的名字
#include <string>
#include <iostream>
using namespace std;
class Screen {
public:
typedef std::string::size_type index;
inline char get(index ht, index wd) const;
Screen():contents("liaojianguo dabendan"), height(1), width(1) { }
private:
std::string contents;
index height, width;
};
char Screen::get(index r, index c) const
{
index row = r * width;
return contents[row + c];
}
int main()
{
Screen c1;
cout << c1.get(1, 1) << endl;
}
输出:
pateo@pateo-B86N53X:~/work/study$ g++ main.cc -o main
pateo@pateo-B86N53X:~/work/study$ ./main
a
类成员中的名字查找
检查成员函数局部作用域中的声明
检查对所有类成员的声明
检查在此成员函数定义之前的作用域中出现的声明
#include <string>
#include <iostream>
using namespace std;
int i = 1;
class Screen {
public:
typedef std::string::size_type index;
inline char get(index ht, index wd) ;
Screen():contents("liaojianguo dabendan"), height(1), width(1) { }
private:
std::string contents;
index height, width;
};
Screen::index set(Screen::index);
char Screen::get(index r, index c)
{
index row = r * width;
return contents[row + c - i];
}
int main()
{
Screen c1;
cout << c1.get(1, 1) << endl;
}
输出:
pateo@pateo-B86N53X:~/work/study$ g++ main.cc -o main
pateo@pateo-B86N53X:~/work/study$ ./main
i
pateo@pateo-B86N53X:~/work/study$
#include <string>
#include <iostream>
using namespace std;
int i = 1;
class Screen {
public:
typedef std::string::size_type index;
inline char get(index ht, index wd) ;
Screen():contents("liaojianguo dabendan"), height(1), width(1) { }
private:
std::string contents;
index height, width;
};
Screen::index set(Screen::index);
Screen::index set(Screen::index i)
{
cout << "--------------" << endl;
return i + 2;
}
char Screen::get(index r, index c)
{
index row = r * width;
row = set(row);
return contents[row + c - i];
}
int main()
{
Screen c1;
cout << c1.get(1, 1) << endl;
}
输出:
pateo@pateo-B86N53X:~/work/study$ g++ main.cc -o main
pateo@pateo-B86N53X:~/work/study$ ./main
--------------
o
pateo@pateo-B86N53X:~/work/study$