在C++中,如何定义一个具有私有属性和公有成员函数的Cat类,并通过这些函数来设置和获取名字、年龄、体重和颜色属性?请结合具体的代码示例进行说明。
时间: 2024-11-13 13:36:18 浏览: 37
在C++面向对象编程中,创建一个类涉及到定义其属性和成员函数。以Cat类为例,我们将定义一个包含私有属性和公有成员函数的类,以实现属性的封装和访问控制。下面是一个简单的Cat类定义和相关成员函数实现的示例:
参考资源链接:[C++编程:创建与操作猫类对象](https://wenku.csdn.net/doc/757kyzaaki?spm=1055.2569.3001.10343)
首先,我们定义Cat类,将名字、年龄、体重和颜色定义为私有成员变量,因为它们是类的内部状态,不应该被外部直接访问:
```cpp
class Cat {
private:
std::string name;
int age;
double weight;
std::string color;
};
```
接下来,我们为这些私有属性添加公有的设置(setter)和获取(getter)成员函数。这些函数允许用户间接地访问和修改对象的内部状态:
```cpp
void Cat::setName(std::string newName) {
name = newName;
}
void Cat::setAge(int newAge) {
age = newAge;
}
void Cat::setWeight(double newWeight) {
weight = newWeight;
}
void Cat::setColor(std::string newColor) {
color = newColor;
}
std::string Cat::getName() const {
return name;
}
int Cat::getAge() const {
return age;
}
double Cat::getWeight() const {
return weight;
}
std::string Cat::getColor() const {
return color;
}
```
此外,我们还可以添加一个print成员函数,用于输出Cat对象的全部信息:
```cpp
void Cat::print() const {
std::cout <<
参考资源链接:[C++编程:创建与操作猫类对象](https://wenku.csdn.net/doc/757kyzaaki?spm=1055.2569.3001.10343)
阅读全文
相关推荐


















