2013-07-06 78 views
1

這是我的main.cpp代碼。輸入爲3串和輸出打印出傳遞給它如何解決類中的類型限定符錯誤?

void Display(const String &str1, const String &str2, const String &str3) 
{ 
    cout << "str1 holds \""; 
    str1.print(); // the error is here about the str1 
    cout.flush(); 
    cout << "\" (length = " << str1.length() << ")" << endl; 

    cout << "str2 holds \""; 
    str2.print(); 
    cout.flush(); 
    cout << "\" (length = " << str2.length() << ")" << endl; 

    cout << "str3 holds \""; 
    str3.print(); 
    cout.flush(); 
    cout << "\" (length = " << str3.length() << ")" << endl; 
} 

這3個String對象的值和長度的誤差:

錯誤C2662:「字符串::打印」:不能轉換'this'指針從'const String'到'String &'

這是在我的執行文件文件中:我在這裏做錯了什麼?

void String::print() 
{ 
cout << m_pName << ": "; 
cout << (int)m_str1 << ", "; 
cout << (int)m_str2 << ", "; 
cout << (int)m_str3 << endl; 
} 
+9

製作'的print()''一個const'合格的成員函數:'無效的print()const' –

+1

'(INT)m_str1'看起來很** * *狡猾。至少使用C++風格的轉換,並將變量名改爲有意義的。 –

+0

編程中有一條規則叫DRY--不要重複自己,你的代碼非常糟糕。讓顯示器一次處理一個字符串,你可以節省三次修改相同的東西(或修改一次,忘記其他兩個,並想知道爲什麼它不工作...) – aryjczyk

回答

1

str1是一個constString的參考。

在簡單的話,編譯器要確保str1.print()不會修改str1

因此,它尋找const過載print方法不存在。

充分利用print方法const

class String 
{ 
    ... 

    void print() const; 
       ^^^^^^ 
    ... 
}; 


void String::print() const 
{     ^^^^^ 
... 
} 
相關問題