لا يمكن إجراء عملية strcpy من صفيف ثنائي الأبعاد إلى صفيف ثنائي الأبعاد آخر

StackOverflow https://stackoverflow.com//questions/11694899

  •  12-12-2019
  •  | 
  •  

سؤال

كلاهما في عامل التشغيل= في نفس الفئة

هنا هو تعريف الوظيفة.

 void segment::operator=(const segment& w) {

        strcpy(this->phrase, w.getPhrase()); //this line creates a problem.

الخطأ أدناه:

segment.cpp: In member function ‘void segment::operator=(const segment&)’:   
segment.cpp:186: error: passing ‘const segment’ as ‘this’ argument of ‘const char* 
segment::getPhrase()’ discards qualifiers
segment.cpp:186: error: cannot convert ‘char (*)[40]’ to ‘char*’ for argument ‘1’ to ‘char* strcpy(char*, const char*)’

 const char* segment::getPhrase(){
        return *phrase;
}

وما فوق هو الوظيفة getPhrase

لا أعرف لماذا لا أستطيع القيام بـ strcpy لذلك.

أحاول إكمال المهمة.

يحرر:

هذا هو النوع من phrase

char phrase[10][40];
هل كانت مفيدة؟

المحلول

هناك مشكلتان.أولا عليك أن تفعل getPhrase طريقة ثابتة.المشكلة الثانية هي ذلك strcpy لا يعمل مع مستوى إضافي من المراوغة.ربما تحتاج إلى شيء مثل هذا:

const char* segment::getPhrase(int index) const { 
    return phrase[index]; 
} 

void segment::operator=(const segment& w) {  
    int index;
    for (index = 0; index < 10; ++index) {
        strcpy(this->phrase[index], w.getPhrase(index)); 
    }
}

يجب عليك استبدال 10 مع ثابت

class segment {
    //other stuff
    static const int kNumPhrases = 10;
    char phrase[kNumPhrases][40];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top