[英]What does char* (int) mean in C++?
我在其中一个项目中有以下代码行:
char* i2txt(int);
我不完全明白它的作用? 凭借我的半知识,我试图使其与浮点数一起工作,所以我将int更改为浮点数,但这给了我一个错误。
char* i2txt(int);
/*vs*/
char* i2txt(float);
错误信息 :
Error LNK2019 unresolved external symbol "char * __cdecl i2txt(float)" (?i2txt@@YAPADM@Z) referenced in function "public: char * __thiscall DapChannel::getDurationTxt(void)" (?getDurationTxt@DapChannel@@QAEPADXZ) PhotoZ DapChannel.obj 1
这声明了一个接受整数并返回char指针的函数。
我猜你更改后得到的错误是链接器错误,告诉你它没有找到带有float参数的i2txt
的定义。 那是因为在其他地方提供的这个函数的定义接受整数参数而不是float。
它声明了一个函数,它接受一个int(按值),并返回一个指向char的点。 给定名称(整数到文本),指针几乎肯定是一个空终止的字符序列,它是数字的文本版本。 指针将指向函数中的静态变量(这意味着它不是线程安全的,如果要保存它,则必须复制生成的文本),或指向动态分配的数组(在这种情况下必须释放它) )。 返回std::string
函数会好得多。
语句char* i2txt(int);
正向声明一个函数i2txt
,它以int
作为输入,并返回一个char*
。
如果在声明之前使用了函数,则会导致错误:
#include <iostream>
int main() {
foo(); // Error: foo not defined
}
void foo() {
std::cout << "Hello, world!";
}
前向声明基本上表示“此函数尚未定义,但我保证最终会定义它。在上面的例子中,它看起来像这样:
#include <iostream>
void foo(); // Forward declaration
int main() {
foo(); // Now we can use it
}
void foo() {
std::cout << "Hello, world!";
}
i2txt(float);
时会出现错误i2txt(float);
? 这会导致错误,因为突然间,没有i2txt(int)
函数可以调用。 因为int
可以隐式转换为float
,编译器仍然允许其他函数调用i2txt(float)
,但是没有提供i2txt(float)
定义,因此存在链接器错误:
#include <iostream>
char* i2txt(float);
int main() {
std::cout << i2txt(10); // Tries calling i2txt(float)
}
// This provides a definition for i2txt(int), but the linker is still missing a definition for i2txt(float)
char* i2txt(int) {
// ... stuff
}
它只是一个带有int
参数和返回char*
的函数声明:
// Declaration :
char* i2txt(int);
// Definition :
char* i2txt(int n)
{
// do something
}
但是发生的error
是因为有一个i2txt
函数的实现,它接受一个int
参数,当你试图更改声明时(特别是如果在静态库中定义的实现),它会给你链接器error
,如下所示:
错误LNK2019:未解析的外部符号“char * __cdecl a(float)”(?a @@ YAPADM @ Z)在...中引用
在正常状态下,如果使用float
值调用i2txt
,它可能会将浮点数转换为int,但是如果您尝试更改i2txt
的声明, i2txt
发生链接错误( 如果定义位于静态库中 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.