consider the following (illustrative .. no NULL checking):

class MS {
public:
    TCHAR _buff[1024];
    MS() { ZeroMemory(_buff,sizeof(_buff)); }
    ~MS() { }
    LPCTSTR operator LPCTSTR() { return _buff; }
    void operator = (LPCTSTR s) { _tcscpy(_buff,s); }
    BOOL operator == (LPCTSTR b) { return _tcscmp(_buff,b)==0; }
    BOOL operator == (MS &m) { return _tcscmp(_buff,m._buff))==0; }
    BOOL operator != (LPCTSTR b) { return _tcscmp(_buff,b)!=0; }
    BOOL operator != (MS &m) { return _tcscmp(_buff,m._buff)!=0; }
};

I want to write a simple if statement such as:

MS a; a=_T("hello");
MS b; b=_T("world");
BOOL match = FALSE;
if (a==b)
{
     match = TRUE;
}

I would like for the comparison "a==b" to perform the _tcscmp, but because of the "operator ()" the function is trying to compare two pointers.

Is there a way to control the precedence of the operators?

The immediate solution is to remove the "operator ()", but, it is a nice convenience function.

Recommended Answers

All 2 Replies

>but because of the "operator ()" the function is trying to compare two pointers.
Congratulations, you've independently discovered one of the reasons why overloading the implicit conversion operator is avoided. You'll notice that the std::string class uses a c_str member function rather than an implicit conversion to const char* for this very reason. It might be convenient, but robust code is more important than programmer convenience.

I'd recommend ditching the operator and using a member function (t_str, maybe? C++ programmers would understand that). That way you can be sure that the conversion will only happen when you want it to happen.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.