strcpy 对指针函数的引用

strcpy a reference to a pointer function

本文关键字:引用 函数 指针 strcpy      更新时间:2023-10-16

我在将我的字符串从用户输入存储到文件名时遇到问题。我需要将文件名保存到 GetfileName() 中。

这是我的代码片段:

 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 class保存 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;
}