zoukankan      html  css  js  c++  java
  • template return value error C2440: “初始化”: 无法从“const T”转换为“const Player *&”

    模板返回值参数,和const T&, T const&问题。

    1.我有如下模板,当类型为不带*参数的时,一切正常

    template<typename T>
    const T & Get(const T & aa)
    {
        const T & b = aa;
        std::cout << b << std::endl;
        return b;
    }
    int main(int, char **)
    {
        int a = 10;
        const int& b = Get<int>(a);    
    }
    

    2. 当使用带*指针类型的话,报错

    error C2440: “初始化”: 无法从“const T”转换为“const Player *&”
    [build]           with
    [build]           [
    [build]               T=Player *
    [build]           ]
    看代码21行,用Player* const& 接就可以正常编译通过,因为T是Player*, 所以引用类型是 Player* const& 不让改指向,const Player* & 可以改指向, 但是不能改值。
    template<typename T>
    const T & Get(const T & aa)
    {
        const T & b = aa;
        std::cout << b << std::endl;
        return b;
    }
    
    class Player
    {
    public:
        void func()
        {
            Player* pp = new Player();
            std::cout << pp << std::endl;
            // Player* const& cc = Get<Player*>(pp); // 这个为正常的情况 
            const Player* & cc = Get<Player*>(pp);// 这个编译报错。
            std::cout << pp << std::endl;
        }
        int a = 10;
    };
    
    int main(int, char **)
    {
        int a = 10;
        const int& b = Get<int>(a);
        Player cc;
        cc.func();  
    }
  • 相关阅读:
    2015年中国500强企业
    汇编语言
    oracle数据库学习路线
    OI生涯回忆录
    NOIP 2020游记
    CF223B Two Strings 题解
    CSP-S 2020游记
    CSP/NOIP 注意事项(2020)
    Luogu P6583 回首过去 题解
    Luogu P2210 Haywire 题解
  • 原文地址:https://www.cnblogs.com/zijian-yang/p/15320898.html
Copyright © 2011-2022 走看看