编辑:紧随其后的代码是工作版本,位于标题中
inline char * operator & (const char String1 [], const MyStringClass & String2)
{
int length = strlen (String1) + String2.Length();
char * pTemp = new char [length + 1];
strcpy (pTemp, String1);
strcat (pTemp, String2.GetStr());
return pTemp;
}
这是我第一次觉得有必要提出问题,因为我自己无法找到有用的信息(通过搜索、谷歌、书籍等)。我的课程书是 C++ Primer 5th Edition,我读过 Ch. 14 涵盖了运算符重载。我不一定要寻找“答案”,而是朝着正确的方向轻推(因为我确实想学习这些东西)。
赋值让我们创建了自己的字符串类并重载了一堆运算符,它们将在任一侧接受一个类对象——除了赋值运算符,它可能只在左侧接受一个类对象。我玩过各种返回类型(这不能是成员函数;试图使它成为友元函数的努力失败了)。
/*
Note: return by value, otherwise I get a warning of returning the address
of a local variable, temporary. But no matter the return type or what I'm
returning, I always get the error: C2677: binary '&' : no global operator
found which takes type 'MyStringClass' (or there is no acceptable
conversion)
*/
MyStringClass operator & (const char String1 [], const MyStringClass & String2)
{
/*
The only requirement is that the left side has const char [] so that
(const char []) & (MyStringClass &) will concatenate. There is no return
type requirement; so, I could either try and return a string object or
an anonymous C-type string.
cout << StringOject1 << endl; // this works
cout << (StringObject1 & "bacon") << endl; // so does this;
// another function overloads & such that: obj & const char [] works
cout << ("bacon" & StringObject1) << endl; // but not this
*/
MyStringClass S (String1); // initialize a new object with String1
S.Concat (String2); // public member function Concat() concatenates String2
// onto String1 in S
return S; // this does not work
/* a different way of trying this... */
int Characters = strlen (String1) + String2.Length();
int Slots = Characters;
char * pTemp = new char [Slots + 1];
strcpy (pTemp, String1);
strcat (pTemp, String2.pString); // this won't work; pString is a private
// member holding char * and inaccessible
// making it pointless to try and initialize and return an object with pTemp
}