返回值为string类型的函数 --- 的输出问题。
时间:2011-12-13
来源:互联网
C/C++ code
#include <iostream> using namespace std; class C { public: string toString() { return "class C"; } }; class B:public C { public: string toString() { return "class B"; } }; class A: public B { public: string toString() { return "class A"; } }; void displayObject(C x) { cout << x.toString() <<endl; } int main(int argc, char* argv[]) { displayObject(A()); displayObject(B()); displayObject(C()); return 0; }
其中函数 void displayObject(C x)编译的时候会报错
C/C++ code
void displayObject(C x) { cout << x.toString() <<endl; }
教材上的输出语句是 cout << x.toString().data() <<endl;
按照教材上的语句编译是可以通过的
我想知道这是为什么?
不知道我这样描述是不是清楚。
程序报错内容:
1>d:\mywork\whypolymorphismdemo\whypolymorphismdemo\filemain.cpp(33) : error C2679: 二进制“<<”: 没有找到接受“std::string”类型的右操作数的运算符(或没有可接受的转换)
作者: tomur 发布时间: 2011-12-13
作者: qscool1987 发布时间: 2011-12-13
作者: whoami1978 发布时间: 2011-12-13
V6下加上#include <string>
我再问个白痴的问题:
<iostream>头文件中 也有 string 类的定义吗?
我是不是可以理解为 cout << x.toString().data() <<endl; 这个语句调用了 string类的成员函数 data()呢?
作者: tomur 发布时间: 2011-12-13
引用 1 楼 qscool1987 的回复:
V6下加上#include <string>
我再问个白痴的问题:
<iostream>头文件中 也有 string 类的定义吗?
我是不是可以理解为 cout << x.toString().data() <<endl; 这个语句调用了 string类的成员函数 data()呢?
哪来的data()?
作者: qscool1987 发布时间: 2011-12-13
// 下面都是输出操作符的重载函数 cout <<s.data(); operator<<(cout,s.data()); // 这个函数不需要#include <string> cout <<s; operator<<(cout,s); // 这个函数必须#include <string>
作者: yisikaipu 发布时间: 2011-12-13
#include <iostream> #include <string> using namespace std; int main(int argc, char* argv[]) { string s("test"); // 下面都是输出操作符的重载函数 cout <<s.data(); operator<<(cout,s.data()); // 这个函数不需要#include <string> cout <<s; operator<<(cout,s); // 这个函数必须#include <string> return 0; }
作者: yisikaipu 发布时间: 2011-12-13
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28