Bonjour à tous.
Dans le cadre de mon project CWS (langage interprété), je dois créer une classe de variables supportant les types de variables majeures.
Pour simplifier la suite de l'écriture du code, j'utilise la surcharge des opérateurs
Voici à quoi ressemble la structure de la classe:
Là où je bloque, c'est que, parti comme ca, je suis bon pour me taper tous les opérateurs pour tous les types (cwsVar, int, float, bool, string).
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 class cwsVar { public: friend ostream &operator<<(ostream &, cwsVar &); cwsVar(); cwsVar(cwsVar &); // should create constructors with different types (int, float, bool & string) int getIntVal(); // float getFloatVal(); // bool getBoolVal(); // string getStringVal(); int getType(); // on getVal, switch type, and return value formatted to wanted type // should first make +, -, / and * operators, and then apply it to +=... with *this = value1 + value2 cwsVar &operator=(int); cwsVar &operator+(int); cwsVar &operator-(int); cwsVar &operator*(int); cwsVar &operator/(int); cwsVar &operator+=(int); cwsVar &operator-=(int); cwsVar &operator*=(int); cwsVar &operator/=(int); // also to do for cwsVar, float, bool and string... something easier ? private: int intVal; float floatVal; bool boolVal; string stringVal; int currentType; };
N'y a-t-il pas une solution plus simple, avec des templates par exemple ? Pourrait-on imaginer avoir une seulement variable de contenu (remplacant intVal, floatVal etc...) avec un template ainsi que des méthode template ?
Sachant qu'une fois la classe terminée, je dois pouvoir faire des opérations simple, comme
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13 cwsVar myVar; myVar = 5; cout << myVar.getIntVal() << endl; myVar += 10; cout << myVar.getIntVal() << endl; myVar -= 7; cout << myVar.getIntVal() << endl; myVar /= 2; cout << myVar.getIntVal() << endl; cout << "Size of cwsVar: " << sizeof(myVar) << endl; cout << (myVar + 5) << endl; cwsVar anotherVar = myVar; cout << anotherVar << endl;
Partager