Bonjour.
J'essaie de faire cet exercicehttps://erlerobotics.gitbooks.io/erl...cises_oop.html dont la solution est donnée :
La solution proposée :Write a program that defines a shape class with a constructor that gives value to width and height. The define two sub-classes triangle and rectangle, that calculate the area of the shape area (). In the main, define two variables a triangle and a rectangle and then call the area() function in this two varibles.
J'étais personnellement parti avec l'idée d'utiliser un constructeur au lieu d'utiliser une fonction "void set_data (float a, float b)" , comme ci-dessous :
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
35
36
37
38
39
40
41
42
43
44
45 // Exercises: OOP#include <iostream> // Exercise 1 using namespace std; class Shape { protected: float width, height; public: void set_data (float a, float b) { width = a; height = b; } }; class Rectangle: public Shape { public: float area () { return (width * height); } }; class Triangle: public Shape { public: float area () { return (width * height / 2); } }; int main (){ Rectangle rect; Triangle tri; rect.set_data (5,3); tri.set_data (2,5); cout << rect.area() << endl; cout << tri.area() << endl; return 0; }
Or, ça ne fonctionne pas et je ne vois pas comment corriger l'erreur ?
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
35
36
37
38
39
40 #include <iostream> using namespace std; class Shape { // The class protected: int hauteur; int largeur; public: // Access specifier Shape(int x, int y) { // Constructor with parameters hauteur = x; largeur = y; } }; class Rectangle : public Shape { public: float area (){ return (hauteur * largeur); } }; class Triangle : public Shape { public: float area() { return (hauteur * largeur/2.0); }; }; int main() { Rectangle r(10, 99); Triangle t(3, 5); // Print values cout << "Aire du rectangle : " <<r.area() << "\n"; cout << "Aire du triangle : " << t.area() << "\n"; return 0; }
Partager