我遇到了谷歌无法解决的问题。为什么 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/