如何从多个不同的派生类创建指向方法构造函数的指针数组

问题描述 投票:0回答:0

你好,我目前正在学习 C++,我想知道是否有可能创建一个指向由派生类构造函数组成的方法的指针数组。

这里是我写的代码,但是我得到了编译错误:

#include <string>
#include <iostream>

class A
{
    public:
        A(){}
        A(const std::string& name):name(name){};
        virtual void define(void) = 0;
    private:
        std::string name;
};

typedef struct objs
{
    std::string name;
    A* (A::*make)(const std::string& name);
}   objs;



class B: public A
{
    public:
        B():A("none"){};
        B(const std::string& name):A(name){};
        A* factory(const std::string& name){return new B(name);};
        void define(void){std::cout << "AVOID ABSTRACT CLASS\n";};
};

class C: public A
{
    public:
        C():A("none"){};
        C(const std::string& name):A(name){};
        A* factory(const std::string& name){return new C(name);};
        void define(void){std::cout << "AVOID ABSTRACT CLASS\n";};
};

class Caller
{
    public:
        Caller(){
            _objs[0].make = B::factory;
            _objs[0].name = "B";
            _objs[1].make = C::factory;
            _objs[1].name = "C";
        }
        A* makeObj(const std::string& objName){
            int i = -1;
            while (++i < 2)
            {
                if (objName == _objs[i].name)
                    return _objs[i].make;
            }
            return NULL;
        };
    private:
        objs _objs[2];
};


int main (int argc, char **argv)
{
    B;
}
test.cpp: In constructor ‘Caller::Caller()’:
test.cpp:41:32: error: invalid use of non-static member function ‘A* B::factory(const string&)’
   41 |             _objs[0].make = B::factory;
      |                                ^~~~~~~
test.cpp:43:32: error: invalid use of non-static member function ‘A* C::factory(const string&)’
   43 |             _objs[1].make = C::factory;
      |                                ^~~~~~~
test.cpp: In member function ‘A* Caller::makeObj(const string&)’:
test.cpp:51:37: error: cannot convert ‘A* (A::*)(const string&)’ {aka ‘A* (A::*)(const std::__cxx11::basic_string<char>&)’} to ‘A*’ in return
   51 |                     return _objs[i].make;
      |                            ~~~~~~~~~^~~~
      |                                     |
      |                                     A* (A::*)(const string&) {aka A* (A::*)(const std::__cxx11::basic_string<char>&)}

这是我得到的编译错误。 基本上我希望 Caller 能够通过他的成员函数 makeObj 向我返回一个指向新 B 或 C 对象的指针,但是这个错误阻止了我怎么办?

c++ inheritance multiple-inheritance
© www.soinside.com 2019 - 2024. All rights reserved.