0

如果我使用模板参数 T=int* 从 CBaseInterface(参见下面的代码)派生,编译器将失败并出现错误 C2555。用于 T 的所有指针类型都会发生这种情况。如果我改用 typedef,则相同的代码可以正常工作。

// If _FALIS is defined, the compiler fails, else it succeeds
// (MS Visual Studio 2013 Update 2, 32 and 64 Bit native C++, Debug build).
#define _FALIS

#ifdef _FALIS
    #define PINT int*   
#else
    typedef int* PINT;
#endif

template <class T>
class CBaseInterface
{
public:
    virtual ~CBaseInterface() {}
    virtual const T Calculate() const = 0;
};

class CCalculator : public CBaseInterface<PINT>
{
public:
    CCalculator() {}
    virtual ~CCalculator() {}

    // error C2555: 'CCalculator::Calculate': 
    // overriding virtual function return type differs and is not 'covariant'
    // from 'CBaseInterface<int *>::Calculate'
    virtual inline const PINT Calculate() const final
    {
       return (PINT)&m_Item;
    }

protected:
    int m_Item = 0;
};

指针类型的问题在哪里?我很困惑,我在 Microsoft 的文档中没有找到适合这种情况的任何内容。

希望您能够帮助我。

4

1 回答 1

1

区别在于const PINT派生类中的含义。

If PINT is a typedef for int *, then const PINT is an int * const (constant pointer to mutable int) - which is fine, that's what the base class function is defined to return. If you use your macro then you have literally const int * (mutable pointer to constant int), which is a completely different type. The typedef is substituted logically into the type system, the macro is substituted blindly as tokens.

One way to rescue this would be to write PINT const or const (PINT) (so the binding of the const is explicit).

And you really shouldn't use macros.

于 2014-06-01T10:09:35.280 回答