博客
关于我
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 调优/优化的 101 个建议!
查看>>
mysql 转义字符用法_MySql 转义字符的使用说明
查看>>
mysql 输入密码秒退
查看>>
mysql 递归查找父节点_MySQL递归查询树状表的子节点、父节点具体实现
查看>>
mysql 通过查看mysql 配置参数、状态来优化你的mysql
查看>>
mysql 里对root及普通用户赋权及更改密码的一些命令
查看>>
Mysql 重置自增列的开始序号
查看>>
mysql 锁机制 mvcc_Mysql性能优化-事务、锁和MVCC
查看>>
MySQL 错误
查看>>
mysql 随机数 rand使用
查看>>
MySQL 面试题汇总
查看>>
MySQL 面试,必须掌握的 8 大核心点
查看>>
MySQL 高可用性之keepalived+mysql双主
查看>>
MySQL 高性能优化规范建议
查看>>
mysql 默认事务隔离级别下锁分析
查看>>
Mysql--逻辑架构
查看>>
MySql-2019-4-21-复习
查看>>
mysql-5.6.17-win32免安装版配置
查看>>
mysql-5.7.18安装
查看>>
MySQL-Buffer的应用
查看>>