I have overloaded the operator << to display a defined type...for that I have declared that function as a friend and I have define two get functions..but for some reason It's not working..any help?
Neither declaring the functions as a friend not doing it...it says that get_r() is not in the scope...doing it like this get_r(a)...doing it like this a.get_r it doesnt give any problem...
class foo{
private:
int value;
public:
int get() const{ //so we can use it with constant objects
return value;
}
};
std::ostream& operator<<( //+no need to be friend
std::ostream &out,
const foo &a //so we can use it with temporaries and constant objects
)
{
out << "Value: " << a.get() << '\n'; //+because we use the public interface
return out;
}
About get_r(a), I think that there is a proposal to make it equivalent to a.get_r(), in the current standard only the later is valid.
#include <iostream>
#include <type_traits>
template< typename T = double > class complex {
static_assert( std::is_arithmetic<T>::value, "T must be an arithmetic type" ) ;
T r;
T i;
public:
complex() : r(0),i(0) {};
complex( T a ) : r(a), i(0) {};
complex( T a, T b ) : r(a), i(b) {};
T get_r() const { return r ; } //get real part
T get_i () const { return i ; } //get imaginarium part
};
template<typename T> // non-friend, non-member. note: a.get_r(), a.get_i()
std::ostream& operator<< ( std::ostream& os, complex<T>& a) {
return os << "( Parte real " << a.get_r() << ", Parte imaginaria " << a.get_i() << " )" ;
}
int main() {
std::cout<<"TESTEO DE CONSTRUCTOR Y COPY,ASSIGNAMENT, MOVE..ETC\n" ;
complex<> a;
complex<> b(1);
complex<> c(4,5);
a = c;
std::cout << c << '\n' ;
}
#include <iostream>
#include <type_traits>
template< typename T > class complex ; // declare complex
template< typename T > std::ostream& operator<< ( std::ostream& os, complex<T>& a ) ; // declare friend
template< typename T = double > class complex {
static_assert( std::is_arithmetic<T>::value, "T must be an arithmetic type" ) ;
T r;
T i;
public:
complex() : r(0),i(0) {};
complex( T a ) : r(a), i(0) {};
complex( T a, T b ) : r(a), i(b) {};
T get_r() const { return r ; } //get real part
T get_i () const { return i ; } //get imaginarium part
// use <> after the function name to indicate that the friend is a template
friend std::ostream& operator<< <> ( std::ostream& os, complex<T>& a );
};
template<typename T> // define friend function
std::ostream& operator<< ( std::ostream& os, complex<T>& a ) {
return os << "( Parte real " << a.r << ", Parte imaginaria " << a.i << " )" ;
}
int main() {
std::cout<<"TESTEO DE CONSTRUCTOR Y COPY,ASSIGNAMENT, MOVE..ETC\n" ;
complex<> a;
complex<> b(1);
complex<> c(4,5);
a = c;
std::cout << c << '\n' ;
}