c++l类中static成员函数和成员数据变量使用
来源:互联网 发布:海王星证券软件下载 编辑:程序博客网 时间:2024/05/16 09:26
c++中为了保护类的封装性,提出了static成员来代替全局变量,下面我们来了解一下static成员的使用方法:程序通过vs2008调试成功
例一:
#include "stdafx.h"
#include<iostream>
#include<string>
#include<cassert>
#include<malloc.h>
#include<fstream>
class test
{
public:
static void show(void);//static成员函数只能访问static数据成员,不能访问普通的数据成员
private:
static int a;//static数据成员可以类内所有成员函数访问
int b;
};
int test::a = 15;//类static数据成员必须在类声明处外初始化
void test::show (void){std::cout<<test::a<<std::endl;}//类static成员函数必须在类外面定义,在类结构内只能声明
int main(void )
{
test test_1;
test_1.show();//访问类static成员和普通成员一样,但是要注意static成员不能用this指针访问
system("pause");
return 0;
}
例二:记录有多少个test对象被创建
#include "stdafx.h"
#include<iostream>
#include<string>
#include<cassert>
#include<malloc.h>
#include<fstream>
class test
{
public:
test(){a=a+1;}
~test(){}
static void show(void);
private:
static int a;
int b;
};
//void test::initial(int& lhs){test::a = lhs;}
int test::a = 0;
void test::show (void){std::cout<<test::a<<std::endl;}
int main(void )
{
test test_1;//创建一个对象
test_1.show();//输出a=1
test test_2;//创建第二个对象
test_2.show();//输出a=2
system("pause");
return 0;
}
- c++l类中static成员函数和成员数据变量使用
- c++l类中static成员函数和成员数据变量使用
- c++static数据成员和成员函数
- static 静态成员变量 静态成员函数 类中使用
- 【c++】内存偏移、成员函数和成员变量、static成员函数、变量
- java static成员变量和成员函数
- C++类中的static数据成员和static成员函数
- c++static数据成员和成员函数(细嚼慢咽)
- static(c++)静态数据成员和静态成员函数
- 类的static成员变量和成员函数
- 类中的static成员变量和成员函数
- static 数据成员和函数成员
- 【C++】C++ static成员变量与static成员函数
- static成员函数成员变量
- 类的static数据成员和成员函数
- c++:静态成员变量和静态成员函数使用问题
- C++中static成员函数访问非static成员变量
- C++中static成员函数访问非static成员变量
- 浅谈Android五大布局(一)——LinearLayout、FrameLayout和AbsoulteLayout
- 浅谈Android五大布局(二)——RelativeLayout和TableLayout
- AMPS:定时器模块源码解读
- Android RelativeLayout布局属性详解
- 初识大数据
- c++l类中static成员函数和成员数据变量使用
- 使用GDI+进行开发的一些问题(4)
- Vim+ctags+cscope阅读源代码
- CentOS 6.3安装Nvidia驱动
- exists 用法
- Sql Server 常用系统存储过程大全
- CentOS更新163源~
- 标准I/O库
- 随机在圆上生成n个点,这n个点在同一半圆的概率是多少?