属性/字段
1. 属性的定义
2. 属性的示例
#include <iostream>
class Car {
private:
std::string brand; // 私有属性
int year; // 私有属性
public:
// 构造函数
Car(std::string b, int y) : brand(b), year(y) {}
// 公共方法:获取品牌
std::string getBrand() const {
return brand;
}
// 公共方法:获取年份
int getYear() const {
return year;
}
// 公共方法:显示信息
void displayInfo() const {
std::cout << "Brand: " << brand << ", Year: " << year << std::endl;
}
};
int main() {
Car car("Toyota", 2020); // 创建 Car 对象
car.displayInfo(); // 输出:Brand: Toyota, Year: 2020
return 0;
}3. 属性的特性
4. 属性的注意事项
5. 总结
Last updated