I'm learning c++, and just messing around with putting classes in separate files for practice. I have a getter function, which is a string (because the variable is saved as a string). However, from my main function, I am not sure how to call it. I know the problem is probably that I need to include "string" somewhere when I call the object, but I have no idea how to format it.
I know this is a pretty newbie questions, but I couldn't find the answer anywhere. Could someone help me out?
(p.s. i'm not trying to get this specific code to work, since it's useless. I'm just trying to learn how to apply it for future reference).
I'v tried throwing in string in a couple places when calling or creating the object, but always get an error. I know I could get around it by not encapsulating the variable or not having a separate class file, but that's not what I want.
-main.cpp-
#include <iostream>
#include "usernameclass.h"
#include <string>
using namespace std;
int main()
{
usernameclass usernameobject;
usernameobject.getUsername();
return 0;
}
-------------------------------------------------
-usernameclass.h-
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
usernameclass();
std::string getUsername();
void setUsername(std::string name);
askUsername();
private:
std::string usernameVar = "test";
};
#endif
-------------------------------------------------
- usernameclass.cpp-
#include "usernameclass.h"
#include <iostream>
#include "username.h"
#include <string>
using namespace std;
string usernameclass::getUsername(){
return usernameVar;
cout << "test cout" << endl;
}
usernameclass::askUsername(){
string name;
cout << "What is your name?" << endl;
cin >> name;
setUsername(name);
cout << "Ah, so your name is "+usernameVar+", great name I guess!" << endl;
cin.get();
cin.get();
cout << "You're about to do some stuff, so get ready!" << endl;
}
usernameclass::usernameclass(){}
void usernameclass::setUsername(string name){
string* nameptr = &usernameVar;
*nameptr = name;
}
-------------------------------------------------
expected result: runs getUsername() function and returns usernameVar actual result: doesn't run the getUsername() function
Aucun commentaire:
Enregistrer un commentaire