2016-01-29 28 views
-1
#include <iostream> 
#include <string> 
using namespace std; 

class String { 
public: 
    String(){ 
     //default 
     value = 0; 
     name = "noname";   
    } 

    String (int x){ 
     setValue(x); 
    } 

    String (string y){ 
     setName(y); 
    } 

    String (int x ,string y) { 
     setValue(x); 
     setName(y); 
    } 

    void setValue(int x){ 
     value = x; 
    } 

    void setName(string y){ 
     name = y; 
    } 

    int getValue(){ 
     return value; 
    } 

    string getName(){ 
     return name; 
    } 

    int Compare (const char* name1,const char* name2){ 
     const char* n1 = name1; 
     const char* n2 = name2; 

     if (strcmp(n1, n2) != 0) 
      cout <<"test"<<endl; 
    }; 


private: 
    int value; 
    string name; 
    const char* n1; 
    const char* n2; 
}; 

int main() 
{ 
    string str1 ("abcd"); 
    string str2 ("bbbb"); 
    int Compare("abcd", "bbbb"); 

    //String coin1(1,"Penny"); 
    //cout<<"Coin 1 is a "<<coin1.getName()<<" and its worth $"<<coin1.getValue()<<endl; 
    //String coin2(10,"Dime"); 
    //cout<<"Coin 2 is a "<<coin2.getName()<<" and its worth $"<<coin2.getValue()<<endl; 

    return 0; 
} 

我可能會做這個完全錯誤的,但我想不出任何其他辦法做它。我試圖做一個strcmp,允許比較字符串對象到另一個字符串對象或到一個「C」型字符串,但我似乎做錯了。爲什麼我的strcmp構造函數不工作?

+0

這將有助於有更多的細節。主要是'int Compare(「abcd」,「bbbb」);'沒有任何意義。例如,你希望能夠調用'比較(coin1,「abcd」)?或者你可以用'Compare(coin1.getName()。c_str(),「abcd」);'。請編輯您的問題以包含調用您想要執行的比較的一些示例。 –

+0

沒有'strcmp構造函數'這樣的事情。因此不清楚你問的是什麼。所有'n1/n2'變量似乎都是不必要的。 – EJP

回答

2

因爲您沒有實例化您的String對象。

嘗試用以下main()

   int main() 
       { 
        String str1 ("abcd"); // create an instance of String class 
        String str2 ("bbbb"); // create another 
        printf("%i", str1.Compare("abcd", "bbbb")); 
        printf("%i", str2.Compare("abcd", "bbbb")); 
        return 0; 
       } 

您也可以讓你的Compare()方法與實例化的字符串工作代替,因此:

     int Compare (const char* nameOther) 
         { 
          const char* n1 = name.c_str(); 
          const char* n2 = nameOther; 

          int result = strcmp(n1, n2); 
          if (result != 0) 
           cout <<"not equal"<<endl; 
          else 
           cout <<"equal"<<endl; 
          return result; // you forgot the 'return' at Compare(). 
         }; 

然後,你可以這樣做:

  int main() 
      { 
       String str1 ("abcd"); // create an instance of String class 
       String str2 ("bbbb"); // create another 
       printf("%i", str1.Compare("abcd")); 
       printf("%i", str2.Compare("abcd")); 
       return 0; 
      } 

測試完成後,您可以刪除不必要的鱈魚從比較():

     int Compare (const char* nameOther) 
         { 
          return strcmp(name.c_str(), nameOther); 
         }; 
相關問題