鱼C论坛

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

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

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

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

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

x
#include <iostream>
using namespace std;
#include <string>
template<class T>
class Maker
{
        public:
                Maker(T val)
                {
                        this->val =val;
                }
                T getval()
                {
                        return this->val;
                }
        private:
                T val;
};
void printfInt(const Maker<int> &m)
{
        cout<<"val: "<<m.getval(); 
}
int main()
{
        Maker<int> m(20);

        printfInt(m);
        return 0;
}

报错:[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
#include <iostream>
using namespace std;
#include <string>
template<class T>
class Maker
{
public:
    Maker(T val)
    {
        this->val = val;
    }
    T getval() const // <------------------- 注意这里
    {
        return this->val;
    }
private:
    T val;
};
void printfInt(const Maker<int>& m)
{
    cout << "val: " << m.getval();
}
int main()
{
    Maker<int> m(20);

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

使用道具 举报

发表于 2022-5-2 19:15:51 | 显示全部楼层    本楼为最佳答案   
#include <iostream>
using namespace std;
#include <string>
template<class T>
class Maker
{
public:
    Maker(T val)
    {
        this->val = val;
    }
    T getval() const // <------------------- 注意这里
    {
        return this->val;
    }
private:
    T val;
};
void printfInt(const Maker<int>& m)
{
    cout << "val: " << m.getval();
}
int main()
{
    Maker<int> m(20);

    printfInt(m);
    return 0;
}
想知道小甲鱼最近在做啥?请访问 -> 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-10-5 22:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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