Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when inserting string << overload C++

Tags:

c++

I am trying to overload the << operator on a class in C++. Whenever I insert a normal string, like the " " into the output stream I get compilation errors that I cannot make sense of. I have done this once before with no problems, so I am very confused.

friend std::ostream& operator<<(std::ostream& out, Variable v);

std::ostream& operator<<(std::ostream& out, Variable v) {
    out << v.type;
    out << " ";
    out << v.name;
    return out;
}

And here is the output:

src/Variable.cpp: In function 'std::ostream& operator<<(std::ostream&, Variable)':
src/Variable.cpp:35:9: error: no match for 'operator<<' in 'out << " "'
src/Variable.cpp:35:9: note: candidates are:
src/Variable.cpp:33:15: note: std::ostream& operator<<(std::ostream&, Variable)
src/Variable.cpp:33:15: note:   no known conversion for argument 2 from 'const char [2]' to 'Variable'
In file included from /usr/local/Cellar/gcc/4.7.0/gcc/lib/gcc/x86_64-apple-darwin10.8.0/4.7.0/../../../../include/c++/4.7.0/string:54:0,
             from src/../inc/Variable.h:4,
             from src/Variable.cpp:1:
/usr/local/Cellar/gcc/4.7.0/gcc/lib/gcc/x86_64-apple-darwin10.8.0/4.7.0/../../../../include/c++/4.7.0/bits/basic_string.h:2750:5: note: template<class _CharT, class _Traits, class _Alloc> std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/local/Cellar/gcc/4.7.0/gcc/lib/gcc/x86_64-apple-darwin10.8.0/4.7.0/../../../../include/c++/4.7.0/bits/basic_string.h:2750:5: note:   template argument deduction/substitution failed:
src/Variable.cpp:35:9: note:   mismatched types 'const std::basic_string<_CharT, _Traits, _Alloc>' and 'const char [2]'
make: *** [bin/Variable.o] Error 1
like image 566
whwright Avatar asked Dec 09 '25 21:12

whwright


2 Answers

Derp. I did not include iostream. However, this does not make much sense to me... since it worked whenever I did not add a string to the ostream. I would think that the compiler would not be able to find ostream at all, and would complain about that

like image 161
whwright Avatar answered Dec 12 '25 09:12

whwright


#include <utility>
#include <iostream>

template <typename T1, typename T2>
std::ostream& operator<< (std::ostream& out, const std::pair<T1, T2>& v)
{
    out << v.first;
    out << " ";
    out << v.second << std::endl;
    return out;
}

int main()
{
    std::pair<int, int> a = std::make_pair(12, 124);
    std::cout << a << std::endl;
    return EXIT_SUCCESS;
}

Its an example how to declare and implement an operator <<

like image 37
Ilya Lavrenov Avatar answered Dec 12 '25 10:12

Ilya Lavrenov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!