为什么g++在未执行的代码处标记强制转换错误

Why does g++ mark a casting error at not executed code?

本文关键字:错误 转换 代码 g++ 执行 为什么      更新时间:2023-10-16

main:

#include "multiparse.h"
int main()
{
parse_string obj;
obj = "1234";
//int a = obj;
//obj = 1234;
return 0;
}

标题:

class parse_string
{
char* str;
long str_sz;
double val;
bool isnumber;
public:
template<class typename>
parse_string& operator=(typenamet input)
{
//printf("%d == %dn",typeid(input).name(),typeid(const char*).name());
if(typeid(input)==typeid(char*)||typeid(input)==typeid(const char*))
{
str_sz=strlen(input)+1;
if(str==0)
{
str = (char*)malloc(sizeof(char)*str_sz);
}
else
{
str = (char*)realloc(str,sizeof(char)*str_sz);
}
memset(str,0,str_sz);
strcpy(str,input);
this->str_to_num();
isnumber=0;
printf("An");
}
else
{
printf("Bn");
val = (double)input;
this->num_to_str();
isnumber=1;
}
}
};

g++错误:multiparse.h错误:-->"val=(double(input;"处从类型"const char*"到类型"double"的强制转换无效

在我的情况下,这段代码不会被执行——它只会打印"A"而不是"B",但g++不会编译这段代码。我想不通。

即使代码没有执行,它仍然是*.cpp文件的一部分(就像以前的#included一样(。因此,它成为该源的*.obj/*.o文件的一个部分。要做到这一点,编译器需要为*.cpp文件中的所有内容生成machine code(模板的工作方式有点不同,但现在与它们无关(。

换句话说,要获得一个由.obj文件组成的.exe/.lib/.dll文件,需要将要成为所述.obj文件的文件正确编译(转码为machine code(。

我为我的需求找到了一个解决方案,但我认为这不是最好的方法:

parse_string& operator=(char* input)
{
str_sz=strlen(input)+1;
if(str==0)
{
str = (char*)malloc(sizeof(char)*str_sz);
}
else
{
str = (char*)realloc(str,sizeof(char)*str_sz);
}
memset(str,0,str_sz);
strcpy(str,input);
this->str_to_num();
isnumber=0;
return *this;
}
parse_string& operator=(const char* input)
{
str_sz=strlen(input)+1;
if(str==0)
{
str = (char*)malloc(sizeof(char)*str_sz);
}
else
{
str = (char*)realloc(str,sizeof(char)*str_sz);
}
memset(str,0,str_sz);
strcpy(str,input);
this->str_to_num();
isnumber=0;
return *this;
}
parse_string& operator=(char input)
{
val = (double)input;
this->num_to_str();
isnumber=1;
return *this;
}
parse_string& operator=(int input)
{
val = (double)input;
this->num_to_str();
isnumber=1;
return *this;
}
parse_string& operator=(long input)
{
val = (double)input;
this->num_to_str();
isnumber=1;
return *this;
}
parse_string& operator=(unsigned char input)
{
val = (double)input;
this->num_to_str();
isnumber=1;
return *this;
}
parse_string& operator=(unsigned int input)
{
val = (double)input;
this->num_to_str();
isnumber=1;
return *this;
}
parse_string& operator=(unsigned long input)
{
val = (double)input;
this->num_to_str();
isnumber=1;
return *this;
}
parse_string& operator=(double input)
{
val = input;
this->num_to_str();
isnumber=1;
return *this;
}