| bdwg (4) | |
|
In short: I would like to make a function that takes in an instance of a class and accesses it's public variables within the function. ie SetName(Player Mchr, string s) { Mchr.name = s; } I'm not sure what I'm doing wrong, but it seems like the function can't access Mchr.name through Mchr. I'll post my code below in case it's a semantic issue instead of a philosophical one. #include <iostream> #include <string> #include "File.h" using namespace std; int main() { string player_name; cin>> player_name; Player Mchr; SetName(Mchr, player_name); cout<< Mchr.name; int end; cin>> end; return 0; } and in "File.h" #ifndef __Class_Function_Test__File__ #define __Class_Function_Test__File__ #include <iostream> #include <string> using namespace std; class Player { public: Player() { name= "N/A"; } string name; }; void SetName(Player Target, string in_name) { Target.name= in_name; } #endif | |
|
|
|
| moorecm (1826) | |||||
Passing the instance by reference should do the trick.
However, making name private and SetName a member function would be preferred.
| |||||
|
Last edited on
|
|||||
| JLBorges (1756) | |
> void SetName( Player Mchr, string s ) This is pass by value; the function modifies a copy of the object. Pass by reference instead: void SetName( Player& Mchr, string s )
| |
|
|
|
| bdwg (4) | |
| Great! Thanks! | |
|
|
|