【C++】类和对象(六)
文章目录
- 二、static成员
- 概念
- 面试题
- 一个题目
- 三、友元
- 友元函数
- 说明
- 友元类
- 四、内部类(了解)
- 概念:
- 注意:
- 特性:
- 五、匿名对象
书接上回: 【C++】类和对象(五)隐式类型转换
二、static成员
01_31 03 12 01
概念
声明为static的类成员称为类的静态成员,用static修饰的成员变量,称之为静态成员变量;用static修饰的成员函数,称之为静态成员函数。静态成员变量一定要在类外进行初始化
面试题
实现一个类,计算程序中创建出了多少个类对象。
class A { public: A() { ++_scount; } A(const A& t) { ++_scount; } ~A() { --_scount; } //static成员函数没有this指针 static int GetACount() { return _scount; } private: //声明 //静态成员变量 不是属于某一个对象,属于所有对象,属于整个类 static int _scount; }; //定义 int A::_scount = 0; void TestA() { cout public: Date(int year, int month, int day) : _year(year) , _month(month) , _day(day) {} // d1 _cout friend ostream& operator} private: int _year; int _month; int _day; }; ostream& operator _cout _cin d._year; _cin d._month; _cin d._day; return _cin; } int main() { Date d; cin d; cout friend class Date;// 声明日期类为时间类的友元类,则在日期类中就直接访问Time类中的私有成员变量 public: Time(int hour = 0, int minute = 0, int second = 0) : _hour(hour) , _minute(minute) , _second(second) {} private: int _hour; int _minute; int _second; }; class Date { public: Date(int year = 1900, int month = 1, int day = 1) : _year(year) , _month(month) , _day(day) {} void SetTimeOfDate(int hour, int minute, int second) { // 直接访问时间类私有的成员变量 _t._hour = hour; _t._minute = minute; _t._second = second; } private: int _year; int _month; int _day; Time _t; }; public: //B这个类受A类的类域的限制 class B { private: int _b1; }; private: int _a1; int _a2; }; int main() { cout public: A(int a=0) :a(_a) { cout cout public: int func(int n) { //... return n; } }; int main() { //有名对象 A aa1; A aa2(10); //匿名对象 //生命周期只在当前一行,,我们可以看到下一行他就会自动调用析构函数 A(); A(10); //匿名对象在这样场景下就很好用: Solution sl; sl.func(10); //该匿名对象的诞生只是为了调用Sum_Solution(10)这个函数 Solution().func(10); return 0; }
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。