使用引用调用时无法调用没有对象的成员函数 const

Cannot call member function const without object when using call by reference

大家好,我在 'cstring.h' 中定义了以下 class:

namespace BaseTypes {

class CString {
    private:
        character *ptrCString = NULL; //Init pointer always with NULL!
        character *createSafeCString(character cStringToCheck[]);
        size_t inline length(const CString &cString) const;
        size_t inline internalLength();
    public:
        CString(character cstring[]);
        ~CString();
        integer length();
        CString& operator+=(const CString& rhs);
        friend CString operator+(CString lhs, const CString &rhs);
    };

}

和 'cstring.cpp':

namespace BaseTypes {
    //Constructor with a char array
    CString::CString(character cstring[]) {
        ptrCString = createSafeCString(cstring);
    }
    ...
    size_t inline CString::length(const CString &cString) const {
        return strlen(cString.ptrCString);
    }
    ...
     CString operator+(CString lhs, const CString &rhs) {
        size_t thisSize = lhs.internalLength();
        size_t rhsSize = CString::length(rhs);
        character *newCString = new character[thisSize + rhsSize + 1];

        strncpy(newCString, lhs.ptrCString, thisSize);
        strncat(newCString, rhs.ptrCString, rhsSize);

        newCString[thisSize + rhsSize] = '[=11=]';
        CString *cString = new CString(newCString);
        return *cString;
    }
}

这给了我一个编译错误:

In function 'BaseTypes::CString BaseTypes::operator+(BaseTypes::CString, BaseTypes::CString&)':
C:\Sources\Projekte\base\types\cstring.cpp:78:45: error: cannot call member function 'size_t BaseTypes::CString::length(const BaseTypes::CString&) const' without object size_t rhsSize = CString::length(rhs);

我卡住了。我没有任何线索。我错过了什么。这不是对 const CString 的引用吗....

问题是您已将 length() 声明为成员函数,并且成员函数期望对给定对象进行操作。通过 CString::length(rhs) 调用带有参数的成员函数将 rhs 的值作为参数传递给函数,但不会告诉 length 方法实际调用哪个对象的方法上,所以没有 this 指针是有意义的。但是,您似乎不需要 length 函数中 this 的值,因此您可以将方法声明为 static,然后通过 CString::length(rhs) 调用它会如您预期的那样工作。

一个更以 OO 为中心的解决方案是将 length 保留为不带参数的非静态成员函数,并使其在 this 而不是显式参数上运行,并且它可以低于 rhs.length()。然而,这只是风格问题,并不比您似乎已经习惯的命令式方法更正确。