鱼C论坛

 找回密码
 立即注册
查看: 1467|回复: 3

[已解决]关于函数模板实例化对象通过普通函数传递对象的问题

[复制链接]
发表于 2022-5-2 18:24:23 | 显示全部楼层 |阅读模式

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

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

x
  1. #include <iostream>
  2. using namespace std;
  3. #include <string>
  4. template<class T>
  5. class Maker
  6. {
  7.         public:
  8.                 Maker(T val)
  9.                 {
  10.                         this->val =val;
  11.                 }
  12.                 T getval()
  13.                 {
  14.                         return this->val;
  15.                 }
  16.         private:
  17.                 T val;
  18. };
  19. void printfInt(const Maker<int> &m)
  20. {
  21.         cout<<"val: "<<m.getval();
  22. }
  23. int main()
  24. {
  25.         Maker<int> m(20);

  26.         printfInt(m);
  27.         return 0;
  28. }
复制代码


报错:[Error] passing 'const Maker<int>' as 'this' argument of 'T Maker<T>::getval() [with T = int]' discards qualifiers [-fpermissive]

问题:为什么会报错?  如何解决?
这里不加const 就没事 但是,加上就会报错
最佳答案
2022-5-2 19:15:51
  1. #include <iostream>
  2. using namespace std;
  3. #include <string>
  4. template<class T>
  5. class Maker
  6. {
  7. public:
  8.     Maker(T val)
  9.     {
  10.         this->val = val;
  11.     }
  12.     T getval() const // <------------------- 注意这里
  13.     {
  14.         return this->val;
  15.     }
  16. private:
  17.     T val;
  18. };
  19. void printfInt(const Maker<int>& m)
  20. {
  21.     cout << "val: " << m.getval();
  22. }
  23. int main()
  24. {
  25.     Maker<int> m(20);

  26.     printfInt(m);
  27.     return 0;
  28. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-5-2 19:15:51 | 显示全部楼层    本楼为最佳答案   
  1. #include <iostream>
  2. using namespace std;
  3. #include <string>
  4. template<class T>
  5. class Maker
  6. {
  7. public:
  8.     Maker(T val)
  9.     {
  10.         this->val = val;
  11.     }
  12.     T getval() const // <------------------- 注意这里
  13.     {
  14.         return this->val;
  15.     }
  16. private:
  17.     T val;
  18. };
  19. void printfInt(const Maker<int>& m)
  20. {
  21.     cout << "val: " << m.getval();
  22. }
  23. int main()
  24. {
  25.     Maker<int> m(20);

  26.     printfInt(m);
  27.     return 0;
  28. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-5-3 07:17:55 | 显示全部楼层
对于 const 对象只能调用 const 函数。楼上已经改好了。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-5-3 22:57:42 | 显示全部楼层
永恒的蓝色梦想 发表于 2022-5-3 07:17
对于 const 对象只能调用 const 函数。楼上已经改好了。

哦哦哦,被const修饰了就成为了常对象,常对象只能调用常函数
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-5-20 20:27

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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