如何在C++中创建没有无参数构造函数的接口?

jac*_*kie 1 c++

如何隐藏消费者的默认构造函数?我试图私下写,但有编译问题.

解决方案是:

class MyInterface
{
public:
            MyInterface(SomeController *controller) {}
};

class Inherited : public MyInterface
{

private:
            Inherited () {}
public:
            Inherited(SomeController *controller)
            {
            }

};
Run Code Online (Sandbox Code Playgroud)

aJ.*_*aJ. 10

在您的情况下,由于您已经提供了一个带有一个参数的构造函数SomeController*,因此编译器不会为您提供任何默认构造函数.因此,默认构造函数不可用.

MyInterface a;
Run Code Online (Sandbox Code Playgroud)

会导致编译器说没有合适的构造函数.

如果您想使构造函数显式不可用,那么使其与private相同.

编辑您发布的代码:

  • 您需要MyInterface显式调用基类构造函数(带有单个参数).否则,默认情况下,派生类构造函数(Inherited)将查找缺少的Base类默认构造函数.

    class Inherited:public MyInterface {private:Inherited(); 上市:

        Inherited(SomeController *controller):MyInterface(controller)
        {}
    };
    
    Run Code Online (Sandbox Code Playgroud)