+ -
当前位置:首页 → 问答吧 → 返回值为string类型的函数 --- 的输出问题。

返回值为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

V6下加上#include <string>

作者: qscool1987   发布时间: 2011-12-13

不同编译器,对头文件要求不同

作者: whoami1978   发布时间: 2011-12-13

引用 1 楼 qscool1987 的回复:

V6下加上#include <string>

我再问个白痴的问题:
 <iostream>头文件中 也有 string 类的定义吗? 
我是不是可以理解为 cout << x.toString().data() <<endl; 这个语句调用了 string类的成员函数 data()呢?

作者: tomur   发布时间: 2011-12-13

引用 3 楼 tomur 的回复:
引用 1 楼 qscool1987 的回复:

V6下加上#include <string>

我再问个白痴的问题:
<iostream>头文件中 也有 string 类的定义吗?
我是不是可以理解为 cout << x.toString().data() <<endl; 这个语句调用了 string类的成员函数 data()呢?

哪来的data()?

作者: qscool1987   发布时间: 2011-12-13

C/C++ code
    // 下面都是输出操作符的重载函数

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

    cout <<s; 
    operator<<(cout,s); // 这个函数必须#include <string>

作者: yisikaipu   发布时间: 2011-12-13

C/C++ code
#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