[英]C++ How to display/print a string object? cout << int works, cout << string not
我遇到了谷歌無法解決的問題。 為什么該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;
}
您必須包含string
標頭才能獲得重載的operator<<
。
此外,您可能希望返回一個const string&
而不是getval
中的string
,更改構造函數以接受const string&
而不是string
,並更改display
以接受const MyClass& ob
以避免不必要的復制。
我不知道什么對你有用,或者如果你已經修復它但我正在研究這個...對於你的cout你必須把這行作為cout <<“在這里插入字符串”<< endl; 你不是把第二個<<放在字符串后面。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.