Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string.h>
- using namespace std;
- class Chaine
- {
- public:
- //Constructeur avec paramètre " une chaine " , sert aussi comme opérateur de conversion "any string" => Chaine Objet
- Chaine(const char * ch);
- //Surcharge du constructeur avec paramètre " longueur de la chaine "
- Chaine(const int x);
- //Surcharge de l'opérateur =
- Chaine operator=(const Chaine &object);
- //Surcharge de l'opérateur +
- Chaine operator+(const Chaine &object);
- //Surcharge de l'opérateur +=
- Chaine operator+=(const Chaine &object);
- //Surcharge de l'opérateur << par une fonction globale
- friend std::ostream& operator<<(std::ostream& out, const Chaine &object);
- //Destructeur
- /*~Chaine();*/
- private:
- char * theString;
- int length;
- };
- //Définition du constructeur à paramètre chaine de caractère
- Chaine::Chaine(const char * ch)
- {
- length = strlen(ch);
- theString = new char[length];
- for (int j = 0;j < length;j++)
- {
- theString[j] = ch[j];
- }
- }
- //Définition du constructeur à paramètre int longueur de la chaine
- Chaine::Chaine(const int x)
- {
- theString = new char[x];
- length = x;
- }
- /*
- Je l'ai commenté car ça donne des exceptions face auxquelles je ne pouvais rien ! :(
- //Définition du destructeur
- Chaine::~Chaine()
- {
- delete[] theString;
- }
- */
- //Définition de la surcharge de l'opérateur =
- Chaine Chaine::operator=(const Chaine &object)
- {
- if (this != &object)
- {
- theString = object.theString;
- this->length = object.length;
- }
- return *this;
- }
- //Définition de la surcharge de l'opérateur +
- Chaine Chaine::operator+(const Chaine &object)
- {
- Chaine newObject(object.length + length);
- for (int i = 0;i<length;i++)
- newObject.theString[i] = theString[i];
- for (int j = 0; j<object.length;j++)
- newObject.theString[j + length] = object.theString[j];
- return newObject;
- }
- //Définition de la surcharge de l'opérateur += ( en utilisant '+' et '=' déjà définis )
- Chaine Chaine::operator+=(const Chaine &object)
- {
- *this = *this + object;
- return *this;
- }
- //Définition de la surcharge de l'opérateur << (comme fonction non membre)
- //En effet << est un opérateur binaire : opérande1 << opérande2
- //Avec opérande1 : cout, opérande2 : chaine
- std::ostream& operator<<(std::ostream &cout, const Chaine &object)
- {
- for(int i=0;i<object.length;i++)
- cout << object.theString[i];
- return cout;
- }
- int main() {
- //Ch1 = SALUT
- Chaine Ch1("SALUT");
- //Ch3, vide de longueur 100
- Chaine Ch3(100);
- //Ch2 = BON
- Chaine Ch2 = "BON";
- //Ch3 = Monsieur
- Ch3 = "Monsieur";
- //Ch1 = BONJOUR
- Ch1 = Ch2 + "JOUR";
- //Ch2 = ,cher,
- Ch2 = ",cher,";
- //Ch1 = Bonjour,cher,
- Ch1 += Ch2;
- //Ch1 = Bonjour,cher,Monsieur
- Ch1 += Ch3;
- cout << Ch1;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement