插入字符串<<时出错重载C ++

时间:2012-07-17 00:08:16

标签: c++

我正在尝试重载<< C ++中的类的运算符。每当我插入一个普通的字符串,就像输入流中的“”一样,我得到的编译错误是我无法理解的。我之前没有遇到任何问题,所以我很困惑。

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;
}

这是输出:

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

3 个答案:

答案 0 :(得分:4)

DERP。我没有包括iostream。然而,这对我来说没有多大意义......因为只要我没有在ostream中添加字符串,它就会起作用。我认为编译器根本无法找到ostream,并会抱怨

答案 1 :(得分:1)

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

它是一个如何声明和实现运算符&lt;&lt;

的示例

答案 2 :(得分:1)

我将在代码中显示您的解决方案

#include <iostream>
#include <string>

/* our custom class */
class Developer 
{
public:
    Developer(const std::string& name, int age) :
     m_name(name), 
     m_age(age) 
    {}

    const std::string& name() const { return m_name; }
    int age() const { return m_age; }

private:
    std::string m_name;
    int m_age;
};

/* overloaded operator<< for output of custom class Developer */
std::ostream& operator<< (std::ostream& stream, const Developer& developer) 
{
    stream << "Developer name:\t" << developer.name() << std::endl;
    stream << "Developer age:\t"  << developer.age()  << std::endl;
    return stream;
}

/* test custom operator<< for class Developer */
int main(int argc, const char** argv) 
{    
    Developer max("Maxim", 23);
    std::cout << max;

    return 0;   
}