How can I call name places from an array in a class object?

58 views Asked by At

How would I connect an array in a header file to a class to print a name from the array?

I have something like the following. I want to use the array from the header file to pick which name to print, so 1 would be Jill. Instead of typing Obj.setFirst_name("Jill") I want to type Obj.setFirst_name(1), how would I do that?

source

#include <iostream>

using namespace std;

class Thing{
private:
    string first_name;

public:
    setFirst_name(string First){
        First_name = First;
    }

    string getFirst_name(){
        return First_name;
    }
};

int main() {
    Thing Obj;
    Obj.setFirst_name(1);
    cout << Obj.getFirst_name(1) << endl;
}

header

string First [2] = {"Jack","Jill"};

I have tried different variations of the getters and setters.

1

There are 1 answers

2
pm100 On

Just do

Thing Obj;
Obj.setFirst_name(First[1]);
cout << Obj.getFirst_name() << endl;

BTW: their is no relationship between the function arg called First and the global array called First. Apart from the fact that the argument hides the global inside that set function

EDIt

or do this

 class Thing{

 private:

    string first_name;

 public:
    setFirst_name(int idx){
       First_name = First[idx];
    }

     string getFirst_name(){
      return First_name;
     }

}

;

now this works

 Obj.setFirst_name(1) ;