+ 6
can you explain this code pleeease
#include <iostream> #include <string> using namespace std; class myClass { public: string name; }; int main() { myClass myObj; myObj.name = "SoloLearn"; cout << myObj.name; return 0; } //Outputs "SoloLearn" my doubts are what name,string and #include<string>do? ---- cant I do this #include <iostream> #include <string> using namespace std; class myClass { public: void name (string name) cout<< name; }; int main() { myClass myObj; myObj.name(solo learn); return 0; }
2 Réponses
+ 3
* string -> It's a variable's data type, an ordered sequence of characters.
* name -> It's the name assigned to the variable type string.
* #include<string> -> It's a library, you need to include the <string> library to use the string data type. Alternatively, you can use a library that includes the string library, for example, #include <iostream>, so you can remove #include <string> from this code.
The second code has some errors:
* void name (string name) -> the code of a method has to be enclosed in Curly Bracket {}.
* myObj.name(solo learn); -> a string has to be enclosed in double quotation marks. myObj.name("solo learn");
Correct code:
#include <iostream>
#include <string>
using namespace std;
class myClass {
public:
void name (string name){
cout<< name;
}
};
int main() {
myClass myObj;
myObj.name("solo learn");
return 0;
}
+ 2
If you do not know what class field nor string is, I'd refer you to C++ tutorials is this app.