Probleme mit Operator überladen



  • Ich habe mir eine String-Klasse geschrieben und möchte dafür den Operator '+' überladen. Ich erhalte folgende Fehlermeldung:

    Compiling...
    main.cpp
    String.cpp
    Generating Code...
    Linking...
    main.obj : error LNK2005: "class String const __cdecl operator+(class String const &,unsigned short const *)" (??H@YA?BVString@@ABV0@PBG@Z) already defined in String.obj
    main.obj : error LNK2005: "class String const __cdecl operator+(class String const &,char const *)" (??H@YA?BVString@@ABV0@PBD@Z) already defined in String.obj
    main.obj : error LNK2005: "class String const __cdecl operator+(class String const &,int)" (??H@YA?BVString@@ABV0@H@Z) already defined in String.obj
    main.obj : error LNK2005: "class String const __cdecl operator+(class String &,class String const &)" (??H@YA?BVString@@AAV0@ABV0@@Z) already defined in String.obj
    Debug/String.exe : fatal error LNK1169: one or more multiply defined symbols found

    Ich habe die String-Klasse mit den Operatoren in einer eigenen .cpp - Datei. Wenn ich die Operatoren dagegen in der main.cpp definiere (wo ich die String-Klasse verwende), funktioniert es.
    Und das ist der Punkt, den ich nicht verstehe.

    Hier noch die Operatoren:

    // String + <type>:
    const String operator+(const String &s1, const wchar_t *s2)
    {
        String tmp(s1);
        tmp += s2;
        return tmp;
    }
    const String operator+(const String &s1, const char *s2)
    {
        String tmp(s1);
        tmp += s2;
        return tmp;
    }
    const String operator+(const String &s1, int s2)
    {
        String tmp(s1);
        tmp += s2;
        return tmp;
    }
    // String + String:
    const String operator+(String &s1, const String &s2)
    {
        String tmp(s1);
        tmp += s2;
        return tmp;
    }
    


  • Optimizer schrieb:

    Ich habe die String-Klasse mit den Operatoren in einer eigenen .cpp - Datei.

    und wie kannst du die klasse dann in einer anderen übersetzungseinheit verwenden?
    mit #include "string.cpp"? dieser satz verwirrt mich.

    ansonsten, wenn du die funktionen in einer header datei hast, schreib mal inline davor.



  • Jo, ich inkludiere String.cpp

    Dank inline geht es jetzt, danke. 🙂


Anmelden zum Antworten