主要:
#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 == %d\n",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("A\n");
}
else
{
printf("B\n");
val = (double)input;
this->num_to_str();
isnumber=1;
}
}
};
g ++错误: multiparse.h错误:在->'val =(double)input;'
时从类型'const char *'强制转换为类型'double'无效在我的情况下,不会执行此代码,它只会打印'A'而不是'B',但是g ++不会编译此代码。 我不知道。
答案 0 :(得分:2)
即使代码没有执行,它仍然是*.cpp
文件的一部分(因为它是#include
d。因此,它成为*.obj
/ {{1 }}文件用于此源。
为此,编译器需要为*.o
文件中的所有内容生成machine code
(模板的工作方式有所不同,但现在不相关了)。
换句话说,要获取由*.cpp
个文件组成的.exe
/ .lib
/ .dll
文件,您需要将这些文件称为{ {1}}个文件可以正确编译(已转换为.obj
)。
答案 1 :(得分:0)
我找到了满足自己需求的解决方案,但我认为这不是最好的方法:
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;
}