VSB*_*VSB 2 c++ string cout class object
我遇到了谷歌无法解决的问题.为什么该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;
}
Run Code Online (Sandbox Code Playgroud)
您必须包含string标头才能获得重载operator<<.
此外,您可能希望返回a const string&而不是stringfrom getval,更改构造函数以接受const string&而不是a string,并更改display为接受a const MyClass& ob以避免不必要的复制.
| 归档时间: |
|
| 查看次数: |
7628 次 |
| 最近记录: |