【发布时间】:2014-03-09 01:43:31
【问题描述】:
我正在为自制的动态数组类进行运算符重载。我也在尝试学习如何使用 *this 指针,但进展并不顺利。以下是我认为需要解释该问题的课程部分和我的代码。
我不明白为什么当 *this 指针指向 + 等式的左侧时,我不能在 *this 指针上调用成员函数。
这里是调用 + 运算符的存根驱动程序:
> 已经超载并且正在工作。
cout << "Please enter a word to add:";
string theWord;
cin >> theWord;
//add word
array1 = array1 + theWord;
cout << "array1: " << array1 << endl;
这里是主要代码:
class DynamicArray
{
public:
//constructor
DynamicArray(int initialcapacity = 10);
//copy constructor
DynamicArray(const DynamicArray& rhs);
//destructor
~DynamicArray();
//operator+ - add a string
DynamicArray operator+(const string& rhs) const;
//operator+ - concatenate another DynamicArray
DynamicArray operator+(const DynamicArray& rhs) const;
//change the capacity of the DynamicArray to the newCapacity -
// may reduce the size of the array - entries past newCapacity will be lost
void resize(int newCapacity);
private:
string* mWords;//pointer to dynamic array of strings
int mNumWords;//the current number of words being kept in the dynamic array
int mCapacity;//the current capacity of the dynamic array (how many strings could fit in the array)
//display all the contained strings (each on a newline) to the output stream provided
void displayContents(ostream& output) const;
//add all the strings contained in the input stream to the dynamic array - resize if necessary
//return how many words are added to the array
int addWords(ifstream &input);
//add a single word to the dynamic array - resize if necessary
void addWord(const string& word);
};
//add a single word to the dynamic array - resize if necessary
void DynamicArray::addWord(const string& word)
{
if (mNumWords >= mCapacity)//need more space?
{
resize(mCapacity + 1);
}
mWords[mNumWords] = word;
mNumWords++;
}
这是我目前正在开发的功能
//operator+ - add a string
DynamicArray DynamicArray::operator+(const string& rhs) const
{
//this doesn't work, why doesn't it, how should/do I use the
//this pointer properly
this.addWord(rhs);
return *this;
}
【问题讨论】:
-
由于
this是一个指针,所以使用->表示法,例如:this->addWord(rhs);。 -
使用 .而不是->。但这仍然行不通。看起来 Paul 下面所说的 addWord 不是 const 函数是问题所在。我必须自己编写而不是调用 addWord()
-
不要“自己编写而不是调用 addWord()”。相反,花时间编写一个带字符串的运算符 +=。然后,您将“一石二鸟”。您现在将拥有 1) 一个有意义的运算符 +=,2) 您的运算符 + 成为一个简单的函数(请参阅下面的答案)。
标签: c++ arrays pointers operator-overloading this