阅读量:3
是的,C++的getter和setter方法可以用于结构体
#include
struct Student {
std::string name;
int age;
// Getter for name
std::string getName() const {
return name;
}
// Setter for name
void setName(const std::string& newName) {
name = newName;
}
// Getter for age
int getAge() const {
return age;
}
// Setter for age
void setAge(int newAge) {
age = newAge;
}
};
int main() {
Student student;
student.setName("John");
student.setAge(20);
std::cout << "Name: " << student.getName() << std::endl;
std::cout << "Age: " << student.getAge() << std::endl;
return 0;
}
在这个例子中,我们定义了一个名为Student的结构体,它包含两个成员变量:name和age。然后,我们为这两个成员变量提供了getter和setter方法。在main函数中,我们创建了一个Student对象,并使用setter方法设置了其属性值,然后使用getter方法获取并打印这些值。
以上就是关于“c++ get set能用于结构体吗”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm