【一天一篇CPP】静态成员
2013-09-26 15:01
183 查看
1.静态数据成员的作用:它是类的不同对象的共享数据,它是全局变量的替代品!!
一个例子:
2.静态函数成员:没有this指针!不能直接使用非静态类成员,若要使用,则必须制定具体对象,而对静态成员,可以直接使用。
注意:
A对于静态函数成员,Box::volume()和box1.volume是等价的,这一点和静态数据成员一样!
B在静态函数成员中 ,由于没有this指针
一个例子【静态数据成员+静态函数成员】
一个例子:
#include <iostream> using namespace std; /* //错误初始化 class Box{ public: Box(int h) : height(h){} static int height; };*/ //正确初始化 class Box{ public: Box() {} Box(int h) { height = 5;}//这句话初始化无效!!!! static int height; }; int Box::height = 10;//需要定义,不是声明!!!int 勿忘记,否则不能使用Box::height和a.height和b.height!!! int main() { Box::height++; cout << Box::height <<endl; Box a; a.height = 20; cout << Box::height <<endl; cout << a.height <<endl; Box b; b.height = 30; cout << Box::height <<endl; cout << a.height <<endl; cout << b.height <<endl; //Box::height和a.height和b.height是等价的 cout << "size = " <<sizeof(Box) <<endl; //size等于1 }
2.静态函数成员:没有this指针!不能直接使用非静态类成员,若要使用,则必须制定具体对象,而对静态成员,可以直接使用。
注意:
A对于静态函数成员,Box::volume()和box1.volume是等价的,这一点和静态数据成员一样!
B在静态函数成员中 ,由于没有this指针
cout << height <<endl;//合法 cout << width <<endl;//非法 cout << a.width <<endl;//合法
一个例子【静态数据成员+静态函数成员】
#include <iostream> using namespace std; class Student{ public: Student(int n,int a,float s) :num(n), age(a),score(s) {} void total(); static float average();//静态函数 private: int num; int age; float score; static float sum; static int count; }; void Student::total() { sum += score;//score是自己的,sum是静态的 count ++; //count是静态的 } float Student::average()//静态函数成员 { return (sum /count); } float Student::sum = 0; int Student::count = 0; int main() { Student stud[3] = { Student(1001,18,70), Student(1002,19,78), Student(1005,20,98), }; for(int i = 0; i < 3; i++) stud[i].total(); cout << "average = " << Student::average() <<endl; return 0; }
相关文章推荐
- 【一天一篇CPP】对象与指针与数组 对象和const和指针和引用
- 【一天一篇CPP】不同类型数据间的转换【转换构造函数、类型转换函数】
- 【一天一篇CPP】C++的虚基类
- Cpp-静态成员
- 【一天一篇CPP】继承和派生:基础知识和继承方式与访问属性
- Cpp_静态成员
- 【一天一篇CPP】对象的动态建立、释放、赋值和赋值
- 【一天一篇CPP】派生类的构造函数和析构函数
- CPP-基础:非静态成员函数后面加const,以及mutable修饰成员变量
- 【一天一篇CPP】基类与派生类的转换(单向:从派生类赋值给基类,舍弃一部分)
- 类的静态成员(外加 头文件.h和实现文件.cpp的用法)
- 【一天一篇CPP】inline、类的存储,简单的构造函数、析构函数
- 【一天一篇CPP】友元和类
- 【一天一篇CPP】类模板
- 【一天一篇CPP】运算符重载--对部分CPP运算符重载
- 【一天一篇CPP】重载运算符的实例
- CPP-基础:类的静态成员
- 【一天一篇CPP】多继承及其二义性(multiple inheritance,也叫多重继承,但不是多层继承)
- 【一天一篇CPP】多态性和虚函数和虚析构函数和纯虚函数和抽象类
- 非静态内部类为什么可以访问外部类的静态成员