logo

Sobrecarga C++ (Função e Operador)

Se criarmos dois ou mais membros com o mesmo nome, mas diferentes em número ou tipo de parâmetro, isso é conhecido como sobrecarga de C++. Em C++, podemos sobrecarregar:

  • métodos,
  • construtores e
  • propriedades indexadas

É porque esses membros possuem apenas parâmetros.

Os tipos de sobrecarga em C++ são:

  • Sobrecarga de função
  • Sobrecarga do operador
Sobrecarga de C++

Sobrecarga de função C++

Sobrecarga de função é definida como o processo de ter duas ou mais funções com o mesmo nome, mas diferentes em parâmetros, é conhecido como sobrecarga de função em C++. Na sobrecarga de função, a função é redefinida usando diferentes tipos de argumentos ou um número diferente de argumentos. É somente através dessas diferenças que o compilador pode diferenciar as funções.

atalhos do linux

O vantagem A vantagem da sobrecarga de funções é que ela aumenta a legibilidade do programa porque você não precisa usar nomes diferentes para a mesma ação.

Exemplo de sobrecarga de função C++

Vamos ver o exemplo simples de sobrecarga de função onde alteramos o número de argumentos do método add().

//programa de sobrecarga de funções quando o número de argumentos varia.

 #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,>

Vejamos o exemplo simples quando o tipo dos argumentos varia.

// Programa de sobrecarga de funções com diferentes tipos de argumentos.

 #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<<>

Sobrecarga e ambigüidade de funções

Quando o compilador não consegue decidir qual função será invocada entre a função sobrecarregada, esta situação é conhecida como sobrecarga de função .

Quando o compilador mostra o erro de ambiguidade, o compilador não executa o programa.

Causas de sobrecarga de função:

  • Conversão de tipo.
  • Função com argumentos padrão.
  • Função com passagem por referência.
Sobrecarga de C++
  • Conversão de tipo:

Vejamos um exemplo simples.

 #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<<>

Onde o tipo de retorno é o tipo de valor retornado pela função.

nome da classe é o nome da classe.

operação do operador é uma função de operador onde op é o operador que está sendo sobrecarregado e o operador é a palavra-chave.

Regras para sobrecarga do operador

  • Os operadores existentes só podem ser sobrecarregados, mas os novos operadores não podem ser sobrecarregados.
  • O operador sobrecarregado contém pelo menos um operando do tipo de dados definido pelo usuário.
  • Não podemos usar a função amigo para sobrecarregar certos operadores. No entanto, a função membro pode ser usada para sobrecarregar esses operadores.
  • Quando os operadores unários são sobrecarregados por meio de uma função-membro, não aceitam argumentos explícitos, mas, se forem sobrecarregados por uma função amiga, recebem um argumento.
  • Quando os operadores binários são sobrecarregados por meio de uma função membro, recebe um argumento explícito e, se são sobrecarregados por meio de uma função amiga, recebe dois argumentos explícitos.

Exemplo de sobrecarga de operadores C++

Vejamos o exemplo simples de sobrecarga de operador em C++. Neste exemplo, a função do operador void operator ++ () é definida (dentro da classe Test).

//programa para sobrecarregar o operador unário ++.

 #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>

Vejamos um exemplo simples de sobrecarga dos operadores binários.

//programa para sobrecarregar os operadores binários.

 #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>