博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于静态成员的一些tips
阅读量:6656 次
发布时间:2019-06-25

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

1.

在类里声明的类的静态成员只是起到一个说明作用,并不会分配成员的变量空间.必须另外在类外面进行声明.

例如,
int Boy::m = 0;
即使不进行初赋值,也要有这样一个定义语句:
int Boy:m;
因为只有这样,编译程序才分配了变量的空间.
否则,便会在链接的时候,出现:
undefined reference to `Boy::m' 这样的错误.

2.

尽管成员是在类的定义体之外定义的,但成员定义就好像它们是在类的作用域中一样。回忆一下,出现在类的定义体之外的成员定义必须指明成员出现在哪个类中: double Sales_item::avg_price( ) const { 

    if ( units_sold ) 
        return revenue/units_sold;     else 
        return 0; } 
在这里,我们用完全限定名Sales_item::avg_price来指出这是类Sales_item作用域中的avg_price成员的定义。一旦看到成员的完全限定名,就知道该定义是在类作用域中。因为该定义是在类作用域中,所以我们可以引用revenue或units_sold,而不必写this->revenue或this->units_sold。

所以,当在类成员函数中访问静态成员变量时无需加上类名。而在对静态变量初始化时,如果位于类作用域之外,那么必须添加类名。

3.

When a static member variable is declared private in a class, how can it be defined?

In the very same way as you define a public static variable in your source(cpp) file.

int static_demo::a = 1;

Access specifiers will not give you error while defining the member. Access specifiers control the access of the member variables, defining a static variable is an excpetion which is allowed.

Compiles cleanly on Ideone .

EDIT: To answer your Q after you posted code.

Your problem is not the definition of the static member. The error is because you are trying to access the private static member inside main. You cannot do that.

Private members of a class can only be accessed inside the class member functions, the same rule applies even to static members. To be able to modify/access your static members you will have to add a member function function to your class and then modify/access the static member inside it.

4.

对象为什么能调用成员函数。是因为有this指针,每个成员函数都需要外界提供this指针,你把成员函数设成回调函数后,那系统要调用回调时,这个this从哪里来呢?所以一般情况下回调函数都设置为静态函数而非成员函数。

绑定回调的时候必须清楚是哪个函数,虚函数的动态方式是不现实的。

最后绑定成员函数并不是不可以的,boost::bind可以了解下它的原理。

转载于:https://www.cnblogs.com/ShaneZhang/archive/2013/06/03/3116028.html

你可能感兴趣的文章
Codeforces VK Cup 2015 A.And Yet Another Bracket Sequence(后缀数组+平衡树+字符串)
查看>>
以Drools5.5为例说明“规则引擎在业务系统中应用”---起始篇
查看>>
linux清理内存
查看>>
查看硬盘负载情况:iostat命令
查看>>
《人月神话》阅读笔记03
查看>>
Linux下防火墙开启相关端口及查看已开启端口
查看>>
PD的CDM模型中的三种实体关系
查看>>
java 版本SQLHelper
查看>>
Hyper-V中的VM如何使用Pass-through Disk
查看>>
黑马程序员—Java动态代理详解
查看>>
PHP发送HEAD方法请求
查看>>
OracleHelper[.Net 连接Oracle数据库的封装类]
查看>>
.net微信公众号开发——消息与事件
查看>>
动态网站维护基本命令
查看>>
透视表提取不反复记录(2)-每一个物品的全部分类
查看>>
基于jQuery/CSS3实现拼图效果的相册插件
查看>>
【问题解决】小数点前面不显示0的问题
查看>>
ios学习笔记(二)第一个应用程序--Hello World
查看>>
Maven学习总结(四)——Maven核心概念——转载
查看>>
怎么用CIFilter给图片加上各种各样的滤镜_2
查看>>