首页 > 解决方案 > 错误 C2440:“正在初始化”:无法从“const mynamespace::mytype*”转换为“const T*”

问题描述

我有这两个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。在这里我可以得到正确的结果,因为Tis just double。在这种情况下,使用 lost const,程序可以通过编译器。

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

标签: c++casting

解决方案


你的演员失去了 const-ness

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

C 风格的演员表起作用的原因是它尝试的演员表之一,const_cast在这种情况下,这可能不是你想要的。


推荐阅读