为什么我的 strcmp 构造函数不工作?

Why is my strcmp constructor not working?

#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;
}

我可能完全错了,但我想不出任何其他方法 it.I我正在尝试制作一个 strcmp,允许将 String 对象与另一个 String 对象进行比较,或者到“C”类型的字符串,但我似乎做错了。

因为您没有实例化 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);
                        };