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

标签 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

最佳答案

德普。我没有包括 iostream。但是,这对我来说没有多大意义......因为只要我没有向 ostream 添加字符串,它就会起作用。我会认为编译器根本无法找到 ostream,并且会对此提示

关于c++ - 插入字符串 << 重载 C++ 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514375/

相关文章:

c++ - 如果延迟很重要,我应该在繁忙的循环中使用 std::this_thread::yield 吗?

c++ - 如何避免打印 cout 语句的终端空间

c++ - Unresolved inclusion : Eclipse Not Showing "Includes" tab under "Paths and Symbols":

c++ - 在消息中包装数据的开销

c++ - 同时修改 std::valarray<T> 的元素是否安全?

C++:当每个线程都应该同时执行 I/O 和 CPU 密集型任务时的多线程设计

c++ - 如何转义 spdlog 消息?

java - Android NDK 中的系统调用

c++ - 编译时坐标生成

c++ - 将文件中的数据读入数组 C++ 时循环跳过行