logo

Surcharge C++ (fonction et opérateur)

Si nous créons deux membres ou plus ayant le même nom mais différents en nombre ou en type de paramètre, on parle de surcharge C++. En C++, on peut surcharger :

  • méthodes,
  • constructeurs, et
  • propriétés indexées

C'est parce que ces membres n'ont que des paramètres.

Les types de surcharge en C++ sont :

  • Surcharge de fonctions
  • Surcharge des opérateurs
Surcharge C++

Surcharge de fonctions C++

La surcharge de fonctions est définie comme le processus consistant à avoir deux fonctions ou plus portant le même nom, mais dont les paramètres sont différents. On parle alors de surcharge de fonctions en C++. Lors de la surcharge de fonctions, la fonction est redéfinie en utilisant soit différents types d'arguments, soit un nombre différent d'arguments. Ce n'est que grâce à ces différences que le compilateur peut différencier les fonctions.

que signifie xdxd

Le avantage L'un des avantages de la surcharge de fonctions est qu'elle augmente la lisibilité du programme car vous n'avez pas besoin d'utiliser des noms différents pour la même action.

Exemple de surcharge de fonctions C++

Voyons l'exemple simple de surcharge de fonction où nous modifions le nombre d'arguments de la méthode add().

// programme de surcharge de fonctions lorsque le nombre d'arguments varie.

 #include using namespace std; class Cal { public: static int add(int a,int b){ return a + b; } static int add(int a, int b, int c) { return a + b + c; } }; int main(void) { Cal C; // class object declaration. cout&lt;<c.add(10, 20)<<endl; cout<<c.add(12, 20, 23); return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> 30 55 </pre> <p>Let&apos;s see the simple example when the type of the arguments vary.</p> <p>// Program of function overloading with different types of arguments.</p> <pre> #include using namespace std; int mul(int,int); float mul(float,int); int mul(int a,int b) { return a*b; } float mul(double x, int y) { return x*y; } int main() { int r1 = mul(6,7); float r2 = mul(0.2,3); std::cout &lt;&lt; &apos;r1 is : &apos; &lt;<r1<< std::endl; std::cout <<'r2 is : ' <<r2<< return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> r1 is : 42 r2 is : 0.6 </pre> <h2>Function Overloading and Ambiguity</h2> <p>When the compiler is unable to decide which function is to be invoked among the overloaded function, this situation is known as <strong>function overloading</strong> .</p> <p>When the compiler shows the ambiguity error, the compiler does not run the program.</p> <p> <strong>Causes of Function Overloading:</strong> </p> <ul> <li>Type Conversion.</li> <li>Function with default arguments.</li> <li>Function with pass by reference.</li> </ul> <img src="//techcodeview.com/img/c-tutorial/89/c-overloading-function-2.webp" alt="C++ Overloading"> <ul> <li>Type Conversion:</li> </ul> <p> <strong>Let&apos;s see a simple example.</strong> </p> <pre> #include using namespace std; void fun(int); void fun(float); void fun(int i) { std::cout &lt;&lt; &apos;Value of i is : &apos; &lt; <i<< std::endl; } void fun(float j) { std::cout << 'value of j is : ' <<j<< int main() fun(12); fun(1.2); return 0; < pre> <p>The above example shows an error &apos; <strong>call of overloaded &apos;fun(double)&apos; is ambiguous</strong> &apos;. The fun(10) will call the first function. The fun(1.2) calls the second function according to our prediction. But, this does not refer to any function as in C++, all the floating point constants are treated as double not as a float. If we replace float to double, the program works. Therefore, this is a type conversion from float to double.</p> <ul> <li>Function with Default Arguments</li> </ul> <p> <strong>Let&apos;s see a simple example.</strong> </p> <pre> #include using namespace std; void fun(int); void fun(int,int); void fun(int i) { std::cout &lt;&lt; &apos;Value of i is : &apos; &lt; <i<< std::endl; } void fun(int a,int b="9)" { std::cout << 'value of a is : ' < <a<< <b<< int main() fun(12); return 0; pre> <p>The above example shows an error &apos;call of overloaded &apos;fun(int)&apos; is ambiguous&apos;. The fun(int a, int b=9) can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int b=9).</p> <ul> <li>Function with pass by reference</li> </ul> <p>Let&apos;s see a simple example.</p> <pre> #include using namespace std; void fun(int); void fun(int &amp;); int main() { int a=10; fun(a); // error, which f()? return 0; } void fun(int x) { std::cout &lt;&lt; &apos;Value of x is : &apos; &lt;<x<< std::endl; } void fun(int &b) { std::cout << 'value of b is : ' < <b<< pre> <p>The above example shows an error &apos; <strong>call of overloaded &apos;fun(int&amp;)&apos; is ambiguous</strong> &apos;. The first function takes one integer argument and the second function takes a reference parameter as an argument. In this case, the compiler does not know which function is needed by the user as there is no syntactical difference between the fun(int) and fun(int &amp;).</p> <h2>C++ Operators Overloading</h2> <p>Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.</p> <p>The advantage of Operators overloading is to perform different operations on the same operand.</p> <p> <strong>Operator that cannot be overloaded are as follows:</strong> </p> <ul> <li>Scope operator (::)</li> <li>Sizeof</li> <li>member selector(.)</li> <li>member pointer selector(*)</li> <li>ternary operator(?:) </li> </ul> <h2>Syntax of Operator Overloading</h2> <pre> return_type class_name : : operator op(argument_list) { // body of the function. } </pre> <p>Where the <strong>return type</strong> is the type of value returned by the function. </p><p> <strong>class_name</strong> is the name of the class.</p> <p> <strong>operator op</strong> is an operator function where op is the operator being overloaded, and the operator is the keyword.</p> <h2>Rules for Operator Overloading</h2> <ul> <li>Existing operators can only be overloaded, but the new operators cannot be overloaded.</li> <li>The overloaded operator contains atleast one operand of the user-defined data type.</li> <li>We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators.</li> <li>When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument.</li> <li>When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments. </li> </ul> <h2>C++ Operators Overloading Example</h2> <p>Let&apos;s see the simple example of operator overloading in C++. In this example, void operator ++ () operator function is defined (inside Test class).</p> <p>// program to overload the unary operator ++.</p> <pre> #include using namespace std; class Test { private: int num; public: Test(): num(8){} void operator ++() { num = num+2; } void Print() { cout&lt;<'the count is: '<<num; } }; int main() { test tt; ++tt; calling of a function 'void operator ++()' tt.print(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The Count is: 10 </pre> <p>Let&apos;s see a simple example of overloading the binary operators.</p> <p>// program to overload the binary operators.</p> <pre> #include using namespace std; class A { int x; public: A(){} A(int i) { x=i; } void operator+(A); void display(); }; void A :: operator+(A a) { int m = x+a.x; cout&lt;<'the result of the addition two objects is : '<<m; } int main() { a a1(5); a2(4); a1+a2; return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The result of the addition of two objects is : 9 </pre></'the></pre></'the></pre></x<<></pre></i<<></pre></i<<></pre></r1<<></pre></c.add(10,>

Voyons l'exemple simple où le type des arguments varie.

// Programme de surcharge de fonctions avec différents types d'arguments.

 #include using namespace std; int mul(int,int); float mul(float,int); int mul(int a,int b) { return a*b; } float mul(double x, int y) { return x*y; } int main() { int r1 = mul(6,7); float r2 = mul(0.2,3); std::cout &lt;&lt; &apos;r1 is : &apos; &lt;<r1<< std::endl; std::cout <<\'r2 is : \' <<r2<< return 0; } < pre> <p> <strong>Output:</strong> </p> <pre> r1 is : 42 r2 is : 0.6 </pre> <h2>Function Overloading and Ambiguity</h2> <p>When the compiler is unable to decide which function is to be invoked among the overloaded function, this situation is known as <strong>function overloading</strong> .</p> <p>When the compiler shows the ambiguity error, the compiler does not run the program.</p> <p> <strong>Causes of Function Overloading:</strong> </p> <ul> <li>Type Conversion.</li> <li>Function with default arguments.</li> <li>Function with pass by reference.</li> </ul> <img src="//techcodeview.com/img/c-tutorial/89/c-overloading-function-2.webp" alt="C++ Overloading"> <ul> <li>Type Conversion:</li> </ul> <p> <strong>Let&apos;s see a simple example.</strong> </p> <pre> #include using namespace std; void fun(int); void fun(float); void fun(int i) { std::cout &lt;&lt; &apos;Value of i is : &apos; &lt; <i<< std::endl; } void fun(float j) { std::cout << \'value of j is : \' <<j<< int main() fun(12); fun(1.2); return 0; < pre> <p>The above example shows an error &apos; <strong>call of overloaded &apos;fun(double)&apos; is ambiguous</strong> &apos;. The fun(10) will call the first function. The fun(1.2) calls the second function according to our prediction. But, this does not refer to any function as in C++, all the floating point constants are treated as double not as a float. If we replace float to double, the program works. Therefore, this is a type conversion from float to double.</p> <ul> <li>Function with Default Arguments</li> </ul> <p> <strong>Let&apos;s see a simple example.</strong> </p> <pre> #include using namespace std; void fun(int); void fun(int,int); void fun(int i) { std::cout &lt;&lt; &apos;Value of i is : &apos; &lt; <i<< std::endl; } void fun(int a,int b="9)" { std::cout << \'value of a is : \' < <a<< <b<< int main() fun(12); return 0; pre> <p>The above example shows an error &apos;call of overloaded &apos;fun(int)&apos; is ambiguous&apos;. The fun(int a, int b=9) can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int b=9).</p> <ul> <li>Function with pass by reference</li> </ul> <p>Let&apos;s see a simple example.</p> <pre> #include using namespace std; void fun(int); void fun(int &amp;); int main() { int a=10; fun(a); // error, which f()? return 0; } void fun(int x) { std::cout &lt;&lt; &apos;Value of x is : &apos; &lt;<x<< std::endl; } void fun(int &b) { std::cout << \'value of b is : \' < <b<< pre> <p>The above example shows an error &apos; <strong>call of overloaded &apos;fun(int&amp;)&apos; is ambiguous</strong> &apos;. The first function takes one integer argument and the second function takes a reference parameter as an argument. In this case, the compiler does not know which function is needed by the user as there is no syntactical difference between the fun(int) and fun(int &amp;).</p> <h2>C++ Operators Overloading</h2> <p>Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.</p> <p>The advantage of Operators overloading is to perform different operations on the same operand.</p> <p> <strong>Operator that cannot be overloaded are as follows:</strong> </p> <ul> <li>Scope operator (::)</li> <li>Sizeof</li> <li>member selector(.)</li> <li>member pointer selector(*)</li> <li>ternary operator(?:) </li> </ul> <h2>Syntax of Operator Overloading</h2> <pre> return_type class_name : : operator op(argument_list) { // body of the function. } </pre> <p>Where the <strong>return type</strong> is the type of value returned by the function. </p><p> <strong>class_name</strong> is the name of the class.</p> <p> <strong>operator op</strong> is an operator function where op is the operator being overloaded, and the operator is the keyword.</p> <h2>Rules for Operator Overloading</h2> <ul> <li>Existing operators can only be overloaded, but the new operators cannot be overloaded.</li> <li>The overloaded operator contains atleast one operand of the user-defined data type.</li> <li>We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators.</li> <li>When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument.</li> <li>When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments. </li> </ul> <h2>C++ Operators Overloading Example</h2> <p>Let&apos;s see the simple example of operator overloading in C++. In this example, void operator ++ () operator function is defined (inside Test class).</p> <p>// program to overload the unary operator ++.</p> <pre> #include using namespace std; class Test { private: int num; public: Test(): num(8){} void operator ++() { num = num+2; } void Print() { cout&lt;<\'the count is: \'<<num; } }; int main() { test tt; ++tt; calling of a function \'void operator ++()\' tt.print(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The Count is: 10 </pre> <p>Let&apos;s see a simple example of overloading the binary operators.</p> <p>// program to overload the binary operators.</p> <pre> #include using namespace std; class A { int x; public: A(){} A(int i) { x=i; } void operator+(A); void display(); }; void A :: operator+(A a) { int m = x+a.x; cout&lt;<\'the result of the addition two objects is : \'<<m; } int main() { a a1(5); a2(4); a1+a2; return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The result of the addition of two objects is : 9 </pre></\'the></pre></\'the></pre></x<<></pre></i<<></pre></i<<></pre></r1<<>

Surcharge de fonctions et ambiguïté

Lorsque le compilateur est incapable de décider quelle fonction doit être invoquée parmi la fonction surchargée, cette situation est appelée surcharge de fonctions .

Lorsque le compilateur affiche l'erreur d'ambiguïté, le compilateur n'exécute pas le programme.

Causes de surcharge de fonctions :

  • Conversion de types.
  • Fonction avec des arguments par défaut.
  • Fonction avec passage par référence.
Surcharge C++
  • Conversion de types :

Voyons un exemple simple.

 #include using namespace std; void fun(int); void fun(float); void fun(int i) { std::cout &lt;&lt; &apos;Value of i is : &apos; &lt; <i<< std::endl; } void fun(float j) { std::cout << \'value of j is : \' <<j<< int main() fun(12); fun(1.2); return 0; < pre> <p>The above example shows an error &apos; <strong>call of overloaded &apos;fun(double)&apos; is ambiguous</strong> &apos;. The fun(10) will call the first function. The fun(1.2) calls the second function according to our prediction. But, this does not refer to any function as in C++, all the floating point constants are treated as double not as a float. If we replace float to double, the program works. Therefore, this is a type conversion from float to double.</p> <ul> <li>Function with Default Arguments</li> </ul> <p> <strong>Let&apos;s see a simple example.</strong> </p> <pre> #include using namespace std; void fun(int); void fun(int,int); void fun(int i) { std::cout &lt;&lt; &apos;Value of i is : &apos; &lt; <i<< std::endl; } void fun(int a,int b="9)" { std::cout << \'value of a is : \' < <a<< <b<< int main() fun(12); return 0; pre> <p>The above example shows an error &apos;call of overloaded &apos;fun(int)&apos; is ambiguous&apos;. The fun(int a, int b=9) can be called in two ways: first is by calling the function with one argument, i.e., fun(12) and another way is calling the function with two arguments, i.e., fun(4,5). The fun(int i) function is invoked with one argument. Therefore, the compiler could not be able to select among fun(int i) and fun(int a,int b=9).</p> <ul> <li>Function with pass by reference</li> </ul> <p>Let&apos;s see a simple example.</p> <pre> #include using namespace std; void fun(int); void fun(int &amp;); int main() { int a=10; fun(a); // error, which f()? return 0; } void fun(int x) { std::cout &lt;&lt; &apos;Value of x is : &apos; &lt;<x<< std::endl; } void fun(int &b) { std::cout << \'value of b is : \' < <b<< pre> <p>The above example shows an error &apos; <strong>call of overloaded &apos;fun(int&amp;)&apos; is ambiguous</strong> &apos;. The first function takes one integer argument and the second function takes a reference parameter as an argument. In this case, the compiler does not know which function is needed by the user as there is no syntactical difference between the fun(int) and fun(int &amp;).</p> <h2>C++ Operators Overloading</h2> <p>Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.</p> <p>The advantage of Operators overloading is to perform different operations on the same operand.</p> <p> <strong>Operator that cannot be overloaded are as follows:</strong> </p> <ul> <li>Scope operator (::)</li> <li>Sizeof</li> <li>member selector(.)</li> <li>member pointer selector(*)</li> <li>ternary operator(?:) </li> </ul> <h2>Syntax of Operator Overloading</h2> <pre> return_type class_name : : operator op(argument_list) { // body of the function. } </pre> <p>Where the <strong>return type</strong> is the type of value returned by the function. </p><p> <strong>class_name</strong> is the name of the class.</p> <p> <strong>operator op</strong> is an operator function where op is the operator being overloaded, and the operator is the keyword.</p> <h2>Rules for Operator Overloading</h2> <ul> <li>Existing operators can only be overloaded, but the new operators cannot be overloaded.</li> <li>The overloaded operator contains atleast one operand of the user-defined data type.</li> <li>We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators.</li> <li>When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument.</li> <li>When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments. </li> </ul> <h2>C++ Operators Overloading Example</h2> <p>Let&apos;s see the simple example of operator overloading in C++. In this example, void operator ++ () operator function is defined (inside Test class).</p> <p>// program to overload the unary operator ++.</p> <pre> #include using namespace std; class Test { private: int num; public: Test(): num(8){} void operator ++() { num = num+2; } void Print() { cout&lt;<\'the count is: \'<<num; } }; int main() { test tt; ++tt; calling of a function \'void operator ++()\' tt.print(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The Count is: 10 </pre> <p>Let&apos;s see a simple example of overloading the binary operators.</p> <p>// program to overload the binary operators.</p> <pre> #include using namespace std; class A { int x; public: A(){} A(int i) { x=i; } void operator+(A); void display(); }; void A :: operator+(A a) { int m = x+a.x; cout&lt;<\'the result of the addition two objects is : \'<<m; } int main() { a a1(5); a2(4); a1+a2; return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The result of the addition of two objects is : 9 </pre></\'the></pre></\'the></pre></x<<></pre></i<<></pre></i<<>

Où le type de retour est le type de valeur renvoyée par la fonction.

nom du cours est le nom de la classe.

opération de l'opérateur est une fonction d'opérateur où op est l'opérateur surchargé et l'opérateur est le mot-clé.

Règles de surcharge des opérateurs

  • Les opérateurs existants peuvent uniquement être surchargés, mais les nouveaux opérateurs ne peuvent pas être surchargés.
  • L'opérateur surchargé contient au moins un opérande du type de données défini par l'utilisateur.
  • Nous ne pouvons pas utiliser la fonction ami pour surcharger certains opérateurs. Cependant, la fonction membre peut être utilisée pour surcharger ces opérateurs.
  • Lorsque les opérateurs unaires sont surchargés via une fonction membre, ils ne prennent aucun argument explicite, mais, s'ils sont surchargés par une fonction amie, ils prennent un argument.
  • Lorsque les opérateurs binaires sont surchargés via une fonction membre, ils prennent un argument explicite, et s'ils sont surchargés via une fonction amie, ils prennent deux arguments explicites.

Exemple de surcharge d'opérateurs C++

Voyons l'exemple simple de surcharge d'opérateurs en C++. Dans cet exemple, la fonction de l'opérateur void Operator ++ () est définie (à l'intérieur de la classe Test).

// programme pour surcharger l'opérateur unaire ++.

 #include using namespace std; class Test { private: int num; public: Test(): num(8){} void operator ++() { num = num+2; } void Print() { cout&lt;<\\'the count is: \\'<<num; } }; int main() { test tt; ++tt; calling of a function \\'void operator ++()\\' tt.print(); return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The Count is: 10 </pre> <p>Let&apos;s see a simple example of overloading the binary operators.</p> <p>// program to overload the binary operators.</p> <pre> #include using namespace std; class A { int x; public: A(){} A(int i) { x=i; } void operator+(A); void display(); }; void A :: operator+(A a) { int m = x+a.x; cout&lt;<\\'the result of the addition two objects is : \\'<<m; } int main() { a a1(5); a2(4); a1+a2; return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The result of the addition of two objects is : 9 </pre></\\'the></pre></\\'the>

Voyons un exemple simple de surcharge des opérateurs binaires.

// programme pour surcharger les opérateurs binaires.

 #include using namespace std; class A { int x; public: A(){} A(int i) { x=i; } void operator+(A); void display(); }; void A :: operator+(A a) { int m = x+a.x; cout&lt;<\\'the result of the addition two objects is : \\'<<m; } int main() { a a1(5); a2(4); a1+a2; return 0; < pre> <p> <strong>Output:</strong> </p> <pre> The result of the addition of two objects is : 9 </pre></\\'the>