文章目录
前言
静态成员的访问和静态成员变量的地址
#include <iostream>
using namespace std;
class Car {
public:
int m_age;
static int m_price;
static void run(int m_price) {
cout << "run(int m_price):" << m_price << endl;
}
};
int Car::m_price = 0;
class BigCar : public Car{
};
int main()
{
//通过对象访问
Car car;
car.m_price = 100;
car.run(car.m_price);
//通过对象指针访问
Car* p = new Car;
p->m_price = 200;
p->run(p->m_price);
//通过类名访问
cout << & Car::m_price << endl;
cout << &BigCar::m_price << endl;
cout << &Car::m_price << endl;
cout << &BigCar::Car::m_price << endl;
return 0;
}
out为
run(int m_price):100
run(int m_price):200
007CC3D4
007CC3D4
007CC3D4
007CC3D4
一个对象计数的问题
#include <iostream>
using namespace std;
class Car {
private:
static int ms_count;//static只有一份内存;private在类外无法访问
public:
Car() {
ms_count++;
}
~Car() {
ms_count--;
}
static int getCount() //加static后可以通过类名访问
{
return ms_count;
}
};
int Car::ms_count= 0;
Car car;
int main()
{
//通过对象访问
Car car0;
//通过对象指针访问
Car* p = new Car;
//通过类名访问
cout << Car::getCount() << endl;
return 0;
}
out
3