2017-10-09 13 views
-5

ユーザー入力からの文字列をfileNameに格納する際に問題があります。私はfileNameをGetfileName()に保存する必要があります。ここでstrcpyポインタ関数への参照

は、私のコードの抜粋です:

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 


} 
+3

filenameは初期化されていないポインタです。コピーする前にメモリにポイントする必要があります。 – Les

+1

致命的なOOPデザイン。責任は最大レベルに分散され、内部は保護されません。どのような部分は、義務を割り当てて解放する責任がありますか? –

+5

'std :: string'を使わない理由は何ですか? – NathanOliver

答えて

1

私はそれをテストし、それを修正するために、ソースコードに小さな変更を加えました。 FrameクラスでSetfileNameというメソッドを作成し、char *fileNamechar 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; 
}