Answer the question
In order to leave comments, you need to log in
How does overloading work in a program?
Hello, kind people
Correct me if I'm wrong: overloading is a predefinition for classes of the existing designation of operations, as a result of class overloading, you can use the operation values familiar to base types.
A predefined function is a function, which means it can be overloaded, that is, create several functions with the same name, but different input parameters.
This is a scientific notation, but I understand it like this - when we perform operations on classes, the compiler does not know what to do, and we explicitly indicate what operations should be performed when calling the operator. - Do I understand correctly, or not?
Please explain how values are passed to overload in this program.
What does kvad mean here, and if you specify k*kvad when calling, then the overload will be called float operator *(float k,kvadrat a) - Right?
#include <iostream>
class Kvadrat{
private:
float storona;
public:
Kvadrat(float a){
storona = a;
}
float ploshad(){
float S = storona*storona;
return S;
}
float operator * (float k){
float S = storona*storona*k*k;
return S;
}
};
int main(){
float a, k;
printf("Vvedite storonu kvadrata: \n");
scanf("%f", &a);
Kvadrat kvad(a);
printf("Ploshad kvadrata: %f\n", kvad.ploshad());
printf("Vvedite koef podobia: \n");
scanf("%f", &k);
printf("Podobniy kvadrat: %f\n", kvad*k);
getchar();
return 0;
}
Answer the question
In order to leave comments, you need to log in
Your operator* is overloaded incorrectly - it must return an object or a reference to an object of its class (i.e. it must return Kvadrat&
): https://en.cppreference.com/w/cpp/language/operators
Parameters are not passed to the overload , but into a function or method (overloaded operators are a special case of a method).
For binary operators, the overloaded operator is called for the class on the left in the expression. For example, for kvad * k - kvad.operator*(k) will be called.
If you write k * kvad, then there will be a compilation error, because the compiler will not be able to convert kvad to float. But you can help by overloading operator float() for Kvadrat.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question