Reputation: 242
I ran into an issue google could not solve. Why is that cout works for an int object but not a string object in the following program?
#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;
}
Upvotes: 2
Views: 8244
Reputation: 21
I don't know what is working for you or if you have fixed it but I just was working on this... for your cout you must put the line as cout << "insert string here" << endl; You're not putting the second << after the string. Hope this helps!
Upvotes: 2
Reputation: 75130
You must include the string
header to get the overloaded operator<<
.
Also you might want to return a const string&
instead of a string
from getval
, change your constructor to accept a const string&
instead of a string
, and change display
to accept a const MyClass& ob
to avoid needless copying.
Upvotes: 9