能举个更简单易懂的例子吗
时间: 2023-12-20 21:19:45 浏览: 25
当我们使用一个汽车类时,我们可以将汽车的属性(如颜色、品牌和型号)定义为类的成员变量,而将汽车的行为(如加速、刹车和转弯)定义为类的成员函数。但是,如果我们需要跟踪所有汽车的数量,我们可以使用一个静态成员变量来实现。例如:
```cpp
#include <iostream>
using namespace std;
class Car {
public:
Car(string c, string b, string m) {
color = c;
brand = b;
model = m;
count++;
}
void drive() {
cout << "The " << color << " " << brand << " " << model << " is driving." << endl;
}
static int getCount() {
return count;
}
private:
string color;
string brand;
string model;
static int count;
};
int Car::count = 0;
int main() {
Car car1("blue", "Toyota", "Camry");
Car car2("red", "Honda", "Civic");
Car car3("silver", "Ford", "Fusion");
cout << "Total cars: " << Car::getCount() << endl;
car1.drive();
car2.drive();
car3.drive();
return 0;
}
```
在这个例子中,我们定义了一个静态成员变量count,用于跟踪汽车的数量。我们在Car类的构造函数中将count加1,并在静态成员函数getCount中返回count的值。在主函数中,我们创建了三个汽车对象,并通过Car::getCount()方法获取汽车的总数。最后,我们调用每个汽车对象的drive()方法,以演示该方法的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)