错误 C2440: 'initializing' : 不能从'const mynamespace::mytype*'转换为'const T*'。

问题描述 投票:0回答:1

我有这两个cpp文件.当我试着编写一个模板函数的时候 Method(),出现C2440错误。

我尝试了三种不同的方法来进行赋值。只有C-style的cast可以通过编译器。

我想知道如何用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呢?

c++ casting
1个回答
3
投票

你的浇注失去了const-ness

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

C型演员之所以能成功,是因为 演员之一 它试图是一个 const_cast 在这种情况下,这很可能不是你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.