C++打印函数报错求助:VS报C2296/C2297错误(首次用继承)
解决Visual Studio的C2296/C2297打印错误
嘿,我懂第一次用继承做学校编程项目就碰编译错误的郁闷,咱们马上把这个问题捋清楚!
错误原因拆解
你遇到的C2296和C2297错误,根源出在两处:
- 第一,
<<运算符用错了对象:字符串字面量(比如"Book #")是const char[]类型,它本身不支持<<运算符——这个运算符是给输出流(比如std::cout)或者std::stringstream用的,不能直接用来拼接字符串赋值给std::string变量。 - 第二,错误取了函数地址而非调用函数:你写的
&getCallNumber()是在取成员函数的地址,而不是调用函数获取它的返回值!编译器看到的是函数指针,完全不是你想要的图书编号、标题这类内容。
正确的解决方法
根据你的需求,分两种场景给你方案:
场景1:直接输出到控制台
如果只是想把内容打印到屏幕,直接用std::cout就行,记得去掉&,直接调用函数:
#include <iostream> // 确保包含这个头文件 // 直接输出 std::cout << "Book #" << getCallNumber() << ", title: " << getTitle() << " by " << getAuthor() << std::endl;
场景2:拼接成std::string变量
如果需要把内容存到std::string里,推荐用std::stringstream(类型安全,能处理不同类型的返回值,比如整数编号+字符串标题):
#include <sstream> // 必须包含这个头文件 #include <string> std::stringstream ss; // 像用cout一样拼接内容 ss << "Book #" << getCallNumber() << ", title: " << getTitle() << " by " << getAuthor(); // 把流里的内容转成string std::string printOutput = ss.str();
如果你的getCallNumber()、getTitle()等函数返回的都是std::string,也可以直接用+拼接(但如果有整数类型返回值,要先用std::to_string()转成字符串):
// 假设getCallNumber()返回int,需要转成string std::string printOutput = "Book #" + std::to_string(getCallNumber()) + ", title: " + getTitle() + " by " + getAuthor();
最后再提醒下
核心就是两个修正:别给字符串字面量用<<,别加&取函数地址——直接调用函数拿返回值就好!
内容的提问来源于stack exchange,提问作者AlphaWeasel
相关产品推荐
相关产品推荐

