鱼C论坛

 找回密码
 立即注册
查看: 962|回复: 2

[已解决]myclass(int x) : x_(x) {};

[复制链接]
发表于 2022-7-9 16:21:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. class myclass
  2. {
  3. public:
  4.     myclass(int x) : x_(x) {};
  5.     int operator()(const int n) const { //这里加上const比较好,保护const int n,n不会被改变
  6.         return n * x_;
  7.     }
  8. private :
  9.     int x_;
  10. };
复制代码



朋友们,看代码碰到这个,我想知道第四行myclass(int x) : x_(x) {};表示什么意思什么作用,没学过想知道为什么这么写,但是在网上又没找到答案,我应该查哪块内容呢?
最佳答案
2022-7-9 17:53:23
本帖最后由 临时号 于 2022-7-9 17:55 编辑

这是myclass这个类的构造函数,作用是将传进来的局部变量x赋值给成员变量x_
https://www.runoob.com/cplusplus/cpp-classes-objects.html

例子:
  1. #include <iostream>
  2. using namespace std;

  3. class myclass
  4. {
  5. public:
  6.     myclass(int x) : x_(x) {};
  7.     int operator()(const int n) const { //这里加上const比较好,保护const int n,n不会被改变
  8.         return n * x_;
  9.     }
  10. private :
  11.     int x_;
  12. };

  13. int main()
  14. {
  15.         myclass my(2);
  16.         cout << my.operator()(5) << endl;
  17.        
  18.         return 0;
  19. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-7-9 17:53:23 | 显示全部楼层    本楼为最佳答案   
本帖最后由 临时号 于 2022-7-9 17:55 编辑

这是myclass这个类的构造函数,作用是将传进来的局部变量x赋值给成员变量x_
https://www.runoob.com/cplusplus/cpp-classes-objects.html

例子:
  1. #include <iostream>
  2. using namespace std;

  3. class myclass
  4. {
  5. public:
  6.     myclass(int x) : x_(x) {};
  7.     int operator()(const int n) const { //这里加上const比较好,保护const int n,n不会被改变
  8.         return n * x_;
  9.     }
  10. private :
  11.     int x_;
  12. };

  13. int main()
  14. {
  15.         myclass my(2);
  16.         cout << my.operator()(5) << endl;
  17.        
  18.         return 0;
  19. }
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-7-9 19:32:08 | 显示全部楼层
本帖最后由 ExiaGN001 于 2022-7-9 20:19 编辑

构造函数,参数是一个int x,用途是将(形参)x赋值给(成员)this->x_ .
如果问题解决,请勿忘记设置最佳答案!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-16 17:58

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表