I am trying to overload the "+" operator to concatenate string using the function strcat(string dest, string src).
Looking at the signature of strcat, uses char *[] type for input arguments and return arguments. Therefore I am fighting with this types which seems to be a thing in cpp.
Here my code:
An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.
(Plus: you should 'announce' your function to main() by a prototype).
I understand that my function operator is a non-static member function already.
Regarding one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration. Would it work if I use a type struct? I saw some exercises that work overloading operator without defining a new class for the type. Does anyone know why?
wait...can the main actually reads the operator overloading function ?
if it is defined under main, there needs to be a prototype for the function above main
If one type is a struct works.
To complete the explanation @jlb gave:
struct: default access specifiers public
class: default access specifiers private
Correct me if I am wrog but if a struct is defined in the class where main is, this struct is accessible by default from all the other classes.
@Flaze07: The prototype was also missing I added it.
It seems you want something which behaves differently than what std::string does. If you want your operator+ to modify the passed 'cadena’ and the ‘size’ of your ‘cadena’ to include the null terminating character, you’re doing great.
You can also simplify your code a bit, if you want:
#include <iostream>
void bFunc();
int main()
{
struct A {
char a {'a'};
};
A my_a;
std::cout << "my_a.a is " << my_a.a << '\n';
bFunc();
return 0;
}
void bFunc()
{
// Error: A is not visible here.
// --> error: 'A' was not declared in this scope
/* A my_b;
std::cout << "my_b.a is " << my_b.a << '\n'; */
}
The error is "‘dumb_array& operator=(dumb_array)’ must be a nonstatic member function".
My questions are:
1) Why cannot be static?
2) Why has to be a member function?
According with what @Enoizat said:
An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration
In my case it is a non-member function and have at least one parameter whose is a class. Then why is the compiler complaining?
Four operators cannot be non-members: operator=, (but operator+= can be non-member), operator(), operator[], and operator->
This is mentioned in the operator overloading overview on cppreference: http://en.cppreference.com/w/cpp/language/operators