2016-03-31 149 views
2

我剛開始學習運算符重載,並且只是玩弄代碼來學習它是如何工作的。所以,我寫了一個添加兩個字符的代碼。例如:'#'+'%'='H',因爲ASCII值增加。'+'運算符在C++中重載

這裏是我的代碼:

#include <iostream> 

using namespace std; 

class Strings { 
//everything is public 
public: 
    char str; 
    //empty constructor 
    Strings(); 
    Strings(char); 
    //operator takes in an object of Strings 
    Strings operator+(Strings); 
}; 

Strings::Strings() 
{} 

//constructor 
Strings::Strings(char a) { 
    str = a; 
} 

//aso is "another string object" 
//makes new empty object "brandNew" 
//brandNew is the two characters added together 
//returns object brandNew 
Strings Strings::operator+(Strings aso) { 
    Strings brandNew; 
    brandNew.str = str + aso.str; 
    return brandNew; 
} 

int main() { 
    Strings a('#'); 
    Strings b('%'); 
    Strings c; 

    //now, we can use + operator to add characters 
    c = a + b; 
    cout << c.str << endl; 
    return 0; 
} 

如果我想要添加兩個字符串?如果我使輸入

Strings a("###"); 
Strings b("%%%"); 

而且我所要的輸出是

HHH 

我怎麼會改變我的代碼,添加兩個字符串?我開始將所有char類型聲明更改爲字符串。我想我必須在運算符函數內部做一個for循環來遍歷兩個輸入的每個字符,同時添加它們。但是,我對它的語法感到困惑,也對如何實現它感到困惑。任何幫助和解釋將不勝感激!

+0

你正在向一個零終止的char數組賦值。你應該有一個char * str; insted,或char str [MAX_SIZE]; –

+0

你想如何添加字符串?你的輸入是字符串,而你想要添加一個字符? 'Strings'只有一個數據成員,它是一個'char'。如果您將其更改爲'string',那麼您將在哪裏存儲此添加項?在發佈之前請仔細考慮。 – anukul

+0

我編輯了上面的問題。我想輸出爲一個字符串「HHH」 – ss1111

回答

0

我會給你一些幫助聲明這個類。

class Strings { 
private: 
    char* str; 
    unsigned int length; 
    unsigned int size; 
public: 
    //constructor 
    Strings(); 
    ~Strings(); 
    Strings(const char*); 
    Strings(const Strings&); 
    //operator 
    Strings operator+(const Strings&); 
    Strings operator+(const char*); 
    Strings operator=(const Strings&); 
    Strings operator=(const char*); 
    Strings operator+=(const Strings&); 
    Strings operator+=(const char*); 
    ///Accessors 
    const char* GetStr()const; 
    unsigned int GetLength()const; 
    unsigned int GetSize()const; 
}; 
+0

您必須至少實現此函數才能擁有一個基本的字符串類,始終注意分配的內存,並檢查是否有足夠的空間來保存給定的字符串 –