1

I'm trying to work with C++ java/C# like interfaces by creating classes that have only pure virtual methods, like the following: (this is just an example)

class IMyInterface
{
public:
    virtual int someFunc() = 0;
    virtual ~IMyInterface() {}
};

Everything is fine until I was stuck implementing a method that exchanges two elements in an array of IMyInterface, since it's not allowed in C++ to instantiate an interface as the compiler will complain about temp not implementing someFunc().

void Exchange(IMyInterface* array, int i, int j)
{
    IMyInterface temp = array[i]; // not allowed
    array[i] = array[j];
    array[j] = temp;
}

so I had to change the interface class definition and get rid of pure virtual function and supply a "default" implementation of the method like so:

class IMyInterface
{
public:
    virtual int someFunc()
    {
        return 0;
    }
    virtual ~IMyInterface() {}
};

The problem is that IMyInterface is not an interface anymore, it doesn't force whatever class that will inherit from it to implement someFunc().

Anyway around this?

4

1 回答 1

2

接口不是完全定义的对象,因此您不能创建它们的实例。它们的大小和结构未定义,因此显然不能在值上下文中创建或使用它们。但是,您可以创建指向接口的指针(Happy Guys?),因为指向对象的指针定义得非常好。示例代码可能变成:

void Exchange(IMyInterface** array, int i, int j)
{
    IMyInterface* temp = array[i]; // allowed :)
    array[i] = array[j];
    array[j] = temp;
}

如果操作应该按值完成,那么模板函数可能更合适。

于 2013-02-19T05:58:18.200 回答