gpt4 book ai didi

c++ - 在 C++ 中使用带有用户输入的 getter 和 setter

转载 作者:行者123 更新时间:2023-12-03 07:00:33 24 4
gpt4 key购买 nike

如果这低于社区的工资等级,请提前道歉。我刚开始学习 OOP,英语不是我的母语。
我刚刚了解了使用 getter 和 setter,以及数据封装的重要性。但是,我在网上看到的所有使用 getter 和 setter 的示例都处理静态值,如下所示:

#include <iostream>
using namespace std;

class Employee {
private:
// Private attribute
int salary;

public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};

int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
我设法通过声明另一组变量并将它们作为参数输入到 setter 中来允许用户输入,如下所示:
int main() {
Employee myObj;
int salary;
cout<<"Enter salary: " << endl;
cin>>salary;
myObj.setSalary(salary);
cout << myObj.getSalary();
return 0;
}
这是允许用户输入的唯一方法吗?除了声明另一组局部变量之外,有没有更优雅的方式来实现这一点?
对不起,如果这是一个初学者问题。我是 C++ 游戏的新手,但我的脚还在湿。

最佳答案

Is this the only way to allow user input? Is there a more elegant way of accomplishing this other than declaring another set of local variables?


(以及来自评论)

I was hoping I could do some variation of myObj.setSalary(cin) so cin would feed the value directly into the getter without me having to pass it into temp variables


我不会混合来自 stdin 的输入使用 setter,最好将它们作为单独的方法:
class foo {
int x;
int other_member;
public:
void set_x(int a) { x = a; }
void set_other_member(int a) { other_member = a; }
void read_x(std::istream& in) {
in >> x;
}
};
这让你写
f.read_x(std::cin);
阅读 x来自 stdin .
请注意,有很多方法可以实现相同的目标,而“优雅”是相当主观的。通常,您会为 operator>> 提供重载。阅读 foo来自流:
std::istream& operator>>(std::istream& in, foo& f) {
int a,b;
in >> a >> b;
f.set_x(a);
f.set_other_member(b);
}
要么这个(使用 setter ),要么让运算符(operator)成为 foo 的 friend (直接访问私有(private))或者您使用 foo::read_x实现它。然后你可以写
foo f;
std::cin >> f;

关于c++ - 在 C++ 中使用带有用户输入的 getter 和 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64369972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com