【发布时间】:2011-08-05 23:37:25
【问题描述】:
我遇到了一个谷歌无法解决的问题。为什么 cout 适用于 int 对象而不适用于以下程序中的字符串对象?
#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;
}
【问题讨论】:
-
“作品”是什么意思?你为什么不让
getval()const 呢? -
为我工作。你的
seen输出和expected输出是什么。它们应该以什么方式不同。
标签: c++ string class object cout