博客
关于我
c++名字查找和作用域的一个例子的感想
阅读量:482 次
发布时间:2019-03-06

本文共 1658 字,大约阅读时间需要 5 分钟。

文件function.cc 

#include 
#include "test.h"using namespace std;int i = 1234; //定义放在.cc文件中,不要放在.h文件中,因为.h文件通常会被多次编译typedef string::size_type size_type1;void Test::print()const{cout << i1 << endl;cout << j << endl;size_type1 s1 = 1234;cout << "s1 is: " << s1 << endl;cout << "big ball1 is:" << Test::big_ball << endl; //类作用域可以用 类名::成员名访问数据成员cout << "class 's member is:" << this->i1 << endl;cout << "global 's member is:" << ::i << endl;//在任何地方,访问全局变量那么前面加::}void Test::fun(Test &t){//下面的i,j查找过程://先找本函数的作用域(从参数部分开始)//在找类作用域//最后找这个函数的外层作用域和全局作用域 if(i1 > 0) {cout << "first private data's sum:" << i + t.i1<< endl;} if(j > 0) {cout <<"second private data's sum:."<< j+ t.j << endl;} Test::pos p1;}

文件test.h

#ifndef TEST_H_INCLUDE#define TEST_H_INCLUDE#include 
#include
using namespace std;class Test{ public: const static int sta_int=1234;//只有const static允许类内初始化 using pos = size_t;//定义一个类型 int big_ball = 1234; Test() = default; Test(int k1,int k2):i1(k1),j(k2){} void print()const; void fun(Test &t);//这个地方,Test还是个不完全类型,可以定义它的引用或者指针 void fun(int k); private: int i1; int j;};inlinevoid print_value(Test t) //类已经定义完毕,这里可以定义类的类型对象t了 { t.print(); }inlinevoid Test::fun(int k) { cout << k << endl; cout << "big ball:"<< Test::big_ball << endl; print_value(*this);//还是先找类作用域内的函数,再找外层(包括全局作用域)内的函数 }#endif

文件main.cc 

#include 
#include "test.h"int main(){Test t1(1,2);Test t2(100,200);Test::pos p1= 111,p2 = 222;//类内定义的类型,可以在任何地方使用,但得加作用域运算符t1.print();t1.fun(t2);t1.fun(1234);cout << p1 << endl;cout << p2 << endl;cout << t1.big_ball << endl;cout << Test::sta_int << endl;return 0;}

转载地址:http://tbvdz.baihongyu.com/

你可能感兴趣的文章
mysql替换表的字段里面内容
查看>>
MySQL最多能有多少连接
查看>>
MySQL最大建议行数 2000w,靠谱吗?
查看>>
MySQL有哪些锁
查看>>
MySQL服务器安装(Linux)
查看>>
mysql服务器查询慢原因分析方法
查看>>
mysql服务无法启动的问题
查看>>
MySQL杂谈
查看>>
mysql权限
查看>>
mysql条件查询
查看>>
MySQL条件查询
查看>>
MySQL架构与SQL的执行流程_1
查看>>
MySQL架构与SQL的执行流程_2
查看>>
MySQL架构介绍
查看>>
MySQL架构优化
查看>>
mysql架构简介、及linux版的安装
查看>>
MySQL查看数据库相关信息
查看>>
MySQL查看表结构和表中数据
查看>>
MySQL查询优化:LIMIT 1避免全表扫描
查看>>
MySQL查询优化之索引
查看>>