如何在类函数中获取用户输入数值?现有代码需实现用户指定增量
实现用户输入增量值的修改方案
没问题!要让用户输入自定义的增量值,只需要在main函数中添加输入逻辑即可,同时我也调整了代码以符合标准C++的规范(比如main函数的返回值)。下面是修改后的完整代码:
#include <iostream> using namespace std; class myClass { friend void increment(myClass *, int); private: int topSecret; public: void display() { cout << "\n The value of the topSecret is " << topSecret; } myClass(); }; // 类的构造函数 myClass::myClass() { topSecret = 100; } // 友元函数定义 void increment(myClass *a, int i) { a->topSecret += i; // 修改私有数据 } // 友元函数使用示例 int main() { // 标准C++要求main返回int类型 myClass x; x.display(); // 添加用户输入增量的逻辑 int userIncrement; cout << "\n请输入要增加的数值:"; cin >> userIncrement; increment(&x, userIncrement); // 将用户输入的增量传入 x.display(); return 0; // 标准返回值 }
代码修改说明:
- 把
main()改成了int main()并添加return 0;,这是标准C++的要求,确保程序能正确退出。 - 新增
int userIncrement;变量,用来存储用户输入的增量值。 - 通过
cout提示用户输入,再用cin读取用户输入的整数。 - 调用
increment函数时,把原来固定的20替换成用户输入的userIncrement。
运行效果示例:
The value of the topSecret is 100 请输入要增加的数值:50 The value of the topSecret is 150
内容的提问来源于stack exchange,提问作者Ahmed Javed
相关产品推荐
相关产品推荐

