#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,允许将String对象与另一个String对象进行比较或者到一个“C”类型的字符串,但我似乎做错了。
答案 0 :(得分: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;
}
在测试之后,您可以从Compare()中删除不必要的代码:
int Compare (const char* nameOther)
{
return strcmp(name.c_str(), nameOther);
};