V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
gargar
V2EX  ›  程序员

c++类的继承问题

  •  
  •   gargar · Nov 30, 2020 · 1709 views
    This topic created in 1981 days ago, the information mentioned may be changed or developed.

    C++渣渣,遇到这个题目,请问 Dan(std::function<Niao* ()> createNiao) 是什么用法?

    还有应该怎么标志,才能知道产生 Egg 的是哪个类( Niao 还是 Yazi )?

    #include <stdexcept>
    #include <functional>
    
    class Dan;
    
    class Niao
    {
    public:
        virtual ~Niao() {};
        virtual Dan* lay() = 0;
    };
    
    class Dan
    {
    public:
        Dan(std::function<Niao* ()> createNiao)
        {
            throw std::logic_error("Waiting to be implemented");
        }
    
        Niao* hatch()
        {
            throw std::logic_error("Waiting to be implemented");
        }
    };
    
    class Yazi : public Niao
    {
    public:
        Yazi()
        {
        }
    
        Dan* lay()
        {
            throw std::logic_error("Waiting to be implemented");
        }
    };
    
    #ifndef RunTests
    int main()
    {
        Niao* yazi = new Yazi();
    
        Dan* dan1 = yazi->lay();
        Niao* childYazi1 = dan1->hatch();
    }
    #endif
    
    3 replies    2020-12-01 15:28:23 +08:00
    across
        1
    across  
       Dec 1, 2020   ❤️ 1
    简单说 std::function 就是类型化的 C++版本函数指针。Niao* () 是函数类型声明,无入参,有返回值。Dan 的构造函数就是设定一个回调而已,看这意思就是 hatch 的时候调用下 createNiao 吧。


    看了半天才发现是拼音····
    PepperEgg
        2
    PepperEgg  
       Dec 1, 2020
    拼音英文混合变成啊 XD
    zhongrs232
        3
    zhongrs232  
       Dec 1, 2020
    看代码莫名喜感哈哈哈哈
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2806 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 624ms · UTC 08:18 · PVG 16:18 · LAX 01:18 · JFK 04:18
    ♥ Do have faith in what you're doing.