幾天前我剛剛開始學習C++。我被賦予了一個任務來展示+運算符重載來連接兩個字符串。我想出了這個解決方案:重載+運算符連接C++中的兩個字符串(有些疑惑)
#include <iostream>
using namespace std;
class Strcpy{
private:
char* wrd;
int len;
public:
Strcpy();
Strcpy(char*);
void Display();
friend Strcpy operator + (Strcpy, Strcpy);
friend Strcpy concatinator(Strcpy, Strcpy);
};
Strcpy :: Strcpy(){
wrd = '\0';
len = 0;
}
Strcpy :: Strcpy(char* w){
int i; len = 0;
for(i = 0; w[i] != '\0' ; i++)
len ++;
wrd = w;
}
void Strcpy :: Display(){
cout << "\nOutput: " << wrd << " "<< len;
}
Strcpy operator + (Strcpy obj1, Strcpy obj2){
Strcpy temp;
int i;
temp.wrd = new char[obj1.len + obj2.len];
temp = concatinator(temp, obj1);
temp = concatinator(temp, obj2);
temp.wrd[temp.len] = '\0';
return temp;
}
Strcpy concatinator(Strcpy obj, Strcpy temp){
for(int i = 0; temp.wrd[i] != '\0'; i++)
{
obj.wrd[obj.len] = temp.wrd[i];
obj.len++;
}
return obj;
}
int main(){
Strcpy word, word_I("Hello"), word_II("World");
word = word_I + word_II;
word.Display();
return 1;
}
要注意的一些事情包括:
- 從字符串常量「字符*」 [-Wwrite串]我意識到這棄用轉換所引起因爲我正在將不可變類型轉換爲可變類型,但是我可以嘗試使用哪種替代方法來擺脫此問題。
- 我想避免使用朋友函數,但重載操作符需要兩個參數,如果它仍然是類成員,則這是不可能的。
下面一行的工程,即使它被更改一樣的,爲什麼會出現這種情況:
temp.wrd = new char[obj1.len + obj2.len]; //changed to temp.wrd = new char[//any number here];
我想避免使用字符串函數,如果這是不可能的。
每當我嘗試下面的形式取得輸入,它崩潰:
char* Strcpy :: get(){ char* temp; cin >> temp; return temp; } int main(){ Strcpy word; Strcpy word_I(word.get()), word_II(word.get()); word = word_I + word_II; word.Display(); return 1; }
最後,我希望得到任何幫助,這將有助於我對現有的解決方案提高和一些解釋,以爲什麼這是更好的,我犯的錯誤。
你有更多的基本問題需要擔心。你正在泄漏記憶。你[違反三項規則](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-ree)。你必須先解決這些問題,然後擔心這一點。 –
此外在得到你不分配任何內存 –
一個類中的A +運算符可以使用。二進制+有一個參數 - 第二個。第一個參數是實例本身(即this)。 – Scheff