返回值为string类型的函数 --- 的输出问题。

UnknowName 2011-12-13 09:09:19
程序如下:

#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)编译的时候会报错

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”类型的右操作数的运算符(或没有可接受的转换)
...全文
668 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
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
  • 打赏
  • 举报
回复
	// 下面都是输出操作符的重载函数

cout <<s.data();
operator<<(cout,s.data()); // 这个函数不需要#include <string>

cout <<s;
operator<<(cout,s); // 这个函数必须#include <string>
qscool1987 2011-12-13
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 tomur 的回复:]
引用 1 楼 qscool1987 的回复:

V6下加上#include <string>

我再问个白痴的问题:
<iostream>头文件中 也有 string 类的定义吗?
我是不是可以理解为 cout << x.toString().data() <<endl; 这个语句调用了 string类的成员函数 data()呢?
[/Quote]
哪来的data()?
UnknowName 2011-12-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 qscool1987 的回复:]

V6下加上#include <string>
[/Quote]
我再问个白痴的问题:
<iostream>头文件中 也有 string 类的定义吗?
我是不是可以理解为 cout << x.toString().data() <<endl; 这个语句调用了 string类的成员函数 data()呢?
whoami1978 2011-12-13
  • 打赏
  • 举报
回复
不同编译器,对头文件要求不同
qscool1987 2011-12-13
  • 打赏
  • 举报
回复
V6下加上#include <string>

65,187

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧