What am i doing wrong? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

What am i doing wrong?

#include <iostream> #include <string> using namespace std; class MyClass { private : string myData ; public : void setMyData(string s) { myData = s; } } ; int main() { MyClass obj; obj.setMyData ("test" ) ; cout << obj; return 0; }

16th Dec 2020, 12:27 AM
Hakam
3 Respuestas
+ 2
I suggest using getters and setters. From what I know they help you prevent errors and help you update components that are dependent on your data. For example if you call your data and you data is null it could potentially throw an error, another example is if you have a variable named "player.position" and you update it, it will also update the player drawable component's position: void setPosition(Point newPosition) { position = newPosition; drawable.position = newPosition; } Also here is your code with the getters and setters implemented ;) #include <iostream> #include <string> using namespace std; class MyClass { private: string data; public: void setData(string s) { data = s; } string getData() { return data; } } ; int main() { MyClass obj; obj.setData("test"); cout << obj.getData(); return 0; } Let me know if you need anything else!
16th Dec 2020, 1:01 AM
Frumkin
Frumkin - avatar
+ 1
Hello, it seems like you want to print obj's data so you need to write "cout << obj.myData;", so to access "myData" on "obj" you also need to declare "myData" in the public section.
16th Dec 2020, 12:38 AM
Frumkin
Frumkin - avatar
+ 1
You can't print MyClass object directly because the compiler doesn't know what to print. A simple way to do is to make another function that returns myData. Or make myData public. And then you can call the function after cout.
16th Dec 2020, 1:13 AM
你知道規則,我也是
你知道規則,我也是 - avatar