-1

I have a class Test which implements to different interface Interface1 and Interface2. There is a FactoryClass that creates an object of this class Test.

class Interface1{   
    virtual void function1() = 0;
};

class Interface2{
       virtual void function2() = 0;
};

class Test(): public Interface1, public Interface2{
void function1()
{
}
void function2()
{
}
};
class FactoryClass
{
    Interface1* createInstance() {
    Interface1* interface1 = new Test();
    return  interface1;        
}
};

void main()
{
    Interface1* int1 = FactoryClass::createInstance();
    int1->function1();

}

I need a solution to access function2 via interface2 wihtout doing new again?

4

1 回答 1

0

在您的代码中,您有很多错误,例如声明函数function1function2私有。

修复错误后,您的代码可以正常编译。

class Interface1
{   
    public:
        virtual void function1() = 0;
};

class Interface2
{   
    public:
        virtual void function2() = 0;
};

class Test : public Interface1, public Interface2
{
public:
    void function1()
    {   

    }
    void function2()
    {

    }
};

class FactoryClass
{
public:
    static auto createInstance() {
        return new Test();        
    }
};

int main()
{
    auto int1 = FactoryClass::createInstance();
    int1->function1();
    int1->function2();
}

现场演示

于 2019-05-08T22:41:05.733 回答