C++ strcpy对指针函数的引用
我无法将用户输入的字符串存储到文件名中。我需要将文件名保存到GetfileName中 以下是我的代码片段:C++ strcpy对指针函数的引用,c++,C++,我无法将用户输入的字符串存储到文件名中。我需要将文件名保存到GetfileName中 以下是我的代码片段: class Frame { char* fileName; Frame* pNext; public: Frame(); ~Frame(); char*& GetfileName() { return fileName; } Frame*& GetpNext() { r
class Frame {
char* fileName;
Frame* pNext;
public:
Frame();
~Frame();
char*& GetfileName() { return fileName; }
Frame*& GetpNext() { return pNext; };
};
void Animation::InsertFrame() {
Frame* frame = new Frame; //used to hold the frames
char* firstName = new char[40];
cout << "Please enter the Frame filename :";
cin.getline(firstName, 40); //enter a filename
strcpy(&frame->GetfileName, firstName); //error, need to copy the inputed name into the function getFileName that returns a char* filename
}
为了测试和修复它,我对您的源代码做了一些小改动。我在Frame类中创建了一个名为SetfileName的方法,并将char*fileName更改为char fileName[40],这样Frame类就保存了fileName的值而不是指针
#include <iostream>
#include <string.h>
using namespace std;
class Frame {
char fileName[40];
Frame *pNext;
public:
Frame() {}
~Frame() {}
const char *GetfileName () { return fileName; }
const Frame *GetpNext () { return pNext; };
void SetfileName(const char *name) { strncpy(fileName, name, sizeof(fileName)); }
void printFileName() { cout << fileName << endl; }
};
void InsertFrame() {
Frame* frame = new Frame; //used to hold the frames
char* firstName = new char[40];
cout << "Please enter the Frame filename :";
cin.getline(firstName, 40); //enter a filename
frame->SetfileName(firstName);
frame->printFileName();
}
int main() {
InsertFrame();
return 0;
}
文件名是一个未初始化的指针,在复制OOP设计之前,您需要它指向内存。责任分配到最大级别,内部无保护。哪个部分负责分配和释放memmory?您不使用std::string的任何原因?@Les我明白了,我该如何修改文件名并将其指向InsertFrame函数中的内存。&frame->GetfileName不会调用缺少括号的函数,并且您操作的值不是frame类中的字符*