博客
关于我
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/

你可能感兴趣的文章
Node-RED中使用node-red-node-ui-iframe节点实现内嵌iframe访问其他网站的效果
查看>>
Node-RED中使用Notification元件显示警告讯息框(温度过高提示)
查看>>
Node-RED中使用range范围节点实现从一个范围对应至另一个范围
查看>>
Node-RED中实现HTML表单提交和获取提交的内容
查看>>
Node-RED中将CSV数据写入txt文件并从文件中读取解析数据
查看>>
Node-RED中建立TCP服务端和客户端
查看>>
Node-RED中建立Websocket客户端连接
查看>>
Node-RED中建立静态网页和动态网页内容
查看>>
Vue3+Element-ul学生管理系统(第二十二课)
查看>>
Node-RED中根据HTML文件建立Web网站
查看>>
Node-RED中解析高德地图天气api的json数据显示天气仪表盘
查看>>
Node-RED中连接Mysql数据库并实现增删改查的操作
查看>>
Node-RED中通过node-red-ui-webcam节点实现访问摄像头并截取照片预览
查看>>
Node-RED中配置周期性执行、指定时间阶段执行、指定时间执行事件
查看>>
Node-RED安装图形化节点dashboard实现订阅mqtt主题并在仪表盘中显示温度
查看>>
Node-RED怎样导出导入流程为json文件
查看>>
Node-RED订阅MQTT主题并调试数据
查看>>
Node-RED通过npm安装的方式对应卸载
查看>>
node-request模块
查看>>
node-static 任意文件读取漏洞复现(CVE-2023-26111)
查看>>