C++ 如何显示/打印字符串对象? cout << int 有效,cout << string 无效

标签 c++ string class object cout

我遇到了谷歌无法解决的问题。为什么 cout 适用于 int 对象而不适用于以下程序中的 string 对象?

#include<iostream>
using namespace std;
class MyClass {
    string val;
public:
    //Normal constructor.
    MyClass(string i) {
        val= i;
        cout << "Inside normal constructor\n";
    }
    //Copy constructor 
    MyClass(const MyClass &o) {
        val = o.val;
        cout << "Inside copy constructor.\n";
    }
    string getval() {return val; }
};
void display(MyClass ob)
{
    cout << ob.getval() << endl;    //works for int but not strings
}
int main()
{
    MyClass a("Hello");
    display(a);
    return 0;
}

最佳答案

您必须包含 string header 以获取重载 operator<< .

您可能还想返回一个 const string&而不是 string来自 getval ,更改您的构造函数以接受 const string&而不是 string , 并更改 display接受const MyClass& ob以避免不必要的复制。

关于C++ 如何显示/打印字符串对象? cout << int 有效,cout << string 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6963685/

相关文章:

c++ - 部分类型作为模板参数 C++

json - 有没有更快的方法来解析 Java 中有效整数的字符串?

c++ - 类中字符串指针的编译错误

python - 是否可以删除(不仅仅是取消链接)类(class)?

javascript - 在不同的类中使用另一个 javascript 类

c++ - 返回类时警告 : control may reach end of non-void function?

c++ - 尝试编译跨平台 C++ 代码。未定义对 C 函数的引用

c++ - 使用虚拟析构函数,我是否需要为每个子类显式声明一个虚拟析构函数?

Java 替代代码作为字符串

c++ - 开发 C++ Web 应用程序的最佳方法是什么?