c++ 作用域


在定义于类外部的成员函数中,形参表和成员函数体都出现在成员名之后。这些都是在类作用域中定义,所以可以不用限定而引用其他成员。例如类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$ 





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值