我是C ++编程语言的新手。这段代码是我在Visual Studio中执行的一个简单的字符串复制功能,但它没有按照我期望的方式工作。
// main file
int _tmain(int argc, _TCHAR* argv[])
{
char source[] = { "Computer" };
int sourcelength = strlen(source);
printf("Source = %s", source);
char* destination = new char[sourcelength];
StringCopyFn(destination, source); // error is on this line
printf("Source = %s", source);
scanf_s("Hello World");
return 0;
}
// String Copy
StringCopyFn::StringCopyFn()
{
}
void StringCopy(char* destination, char* source)
{
int i = 0;
while (source[i] != '\0')
{
destination[i] = source[i];
i++;
}
}
StringCopyFn::~StringCopyFn()
{
}
我收到以下错误消息:
没有构造函数的实例匹配参数列表
如何更正此错误?
答案 0 :(得分:2)
这是StringCopyFn构造函数:
StringCopyFn::StringCopyFn()
{
}
请注意,它需要零参数。
但基于此代码:
StringCopyFn(destination, source);
您似乎打算调用StringCopy()
函数。从你为什么创建StringCopyFn类的问题中不清楚。
答案 1 :(得分:1)
也许,你打算做以下事情:
#include <cstdio>
#include <cstring>
#include <TCHAR.h>
class StringCopyFn {
public:
static void StringCopy(char *destination, char *source);
};
void StringCopyFn::StringCopy(char* destination, char* source){
int i = 0;
while( source[i] != '\0' ){
destination[i] = source[i];
i++;
}
destination[i] = '\0';
}
int _tmain(int argc, _TCHAR* argv[]){
char source[] = { "Computer" };
int sourcelength = strlen(source);
printf("Source = %s", source);
char* destination = new char[sourcelength+1];
StringCopyFn::StringCopy(destination, source);
printf("\ndestination = %s\n", destination);
scanf_s("Hello World");
delete [] destination;
return 0;
}
或
#include <cstdio>
#include <cstring>
#include <TCHAR.h>
struct StringCopyFn {
public:
void operator()(char *destination, char *source){
int i = 0;
while( source[i] != '\0' ){
destination[i] = source[i];
i++;
}
destination[i] = '\0';
}
};
int _tmain(int argc, _TCHAR* argv[]){
char source[] = { "Computer" };
int sourcelength = strlen(source);
printf("Source = %s", source);
char* destination = new char[sourcelength+1];
StringCopyFn()(destination, source);
printf("\ndestination = %s\n", destination);
scanf_s("Hello World");
delete [] destination;
return 0;
}