错误C2440:“正在初始化”:无法从“ const mynamespace :: mytype *”转换为“ const T *”

时间:2020-04-22 16:12:12

标签: c++ casting

我有这两个cpp文件。 当我尝试对模板函数Method()进行编码时,会发生C2440错误。

我尝试了三种不同的方式来完成作业。只有C样式的强制类型转换可以通过编译器。

我想知道如何使用C ++风格。

谢谢:)

FileA:

template <typename T>
int ClassName<T>::Method(params...)
{
    const T* temp = (T*)GetValueArray(); // C-style cast, right √
    const T* temp = GetValueArray(); // no cast, error C2440
    const T* temp = static_cast<T*>(GetValueArray()); // error C2440, reinterpret or 
                                                      // const or dynamic_cast all C2440 
}

_______________

FileB:

typedef double mytype;

const mynamespace::mytype* GetValueArray() const
{
    mynamespace::mytype res[3] = {1,2,3};
    return res;
}

#include <iostream>

typedef double MyType;

const MyType* GetValueArray()
{
    MyType* ptr = new MyType;
    *ptr = 20.20;
    return ptr;
}

template <typename T>
void Method()
{
    const T* temp = (T*)GetValueArray(); // C-style cast, right √
    //const T* temp = GetValueArray(); // no cast, error C2440
    //const T* temp = static_cast<T*>(GetValueArray()); // error C2440, reinterpret or 
                                                      // const or dynamic_cast all C2440
    std::cout << *temp;
}

int main(int argc, char* argv[])
{
    Method<double>();
}

我得到输出20.2。在这里我可以得到正确的结果,因为T只是double。在这种情况下,如果const丢失,则程序可以通过编译器。

但是如果我更改为Method<int>,无论结果是什么(实际上结果是无用的数字),为什么会出现C2440?

1 个答案:

答案 0 :(得分:3)

您的演员表失去了稳定性

const T* temp = static_cast<const T*>(GetValueArray());

C样式强制转换起作用的原因是它尝试使用的one of the castsconst_cast,在这种情况下可能不是您想要的。