0

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.

Edited by jbarwick: n/a

3
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by Narue
0

>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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.