Reputation: 19
I'm new to classes I created a new class to track different details of an account however I was told that the members of my class should be private and to use a getter and setter function. I have look a lots of examples but I can't seem to figure out how to access the private members from my main program. I want the user to enter the different parameters for the account if I make the members public it works just fine how do I add the getters and setters. the private members of my class and whats in main is the only stuff that I need everything else I was adding to try to make it work but i'm really lost. Im using the vector because once i get it to work i'll write a loop to get the data for multiple accounts but right now i'm just trying to get the input stored
class account
{ public
friend void getter(int x);
private:
int a;
char b;
int c;
int d;
};
using namespace std;
void getter (int x)
{
}
int main()
{
vector <account> data1 (0);
account temp;
cin>>temp.a>>temp.b>>temp.c>>temp.d;
data1.push_back(temp);
return 0;
}
Upvotes: 0
Views: 637
Reputation: 64308
Here's an example of get/set methods:
class account
{ public
int getA() const { return a; }
void setA(int new_value) { a = new_value; }
int getB() const { return b; }
void setB(int new_value) { b = new_value; }
int getC() const { return c; }
void setC(int new_value) { c = new_value; }
int getD() const { return d; }
void setD(int new_value) { d = new_value; }
private:
int a;
char b;
int c;
int d;
};
From the main you would use:
int main()
{
vector <account> data1 (0);
account temp;
int a,b,c,d;
cin >> a >> b >> c >> d;
temp.setA(a);
temp.setB(b);
temp.setC(c);
temp.setD(d);
data1.push_back(temp);
return 0;
}
NOTE: Whether having get/set methods in a case like this is a good idea is another issue.
Upvotes: 1
Reputation: 96875
You should have a friend operator overload:
class account
{
friend std::istream& operator>> (std::istream &, account &);
public:
// ...
};
std::istream& operator>> (std::istream& is, account& ac)
{
return is >> ac.a >> ac.b >> ac.c >> ac.d;
}
int main()
{
account temp;
std::cin >> temp;
}
Upvotes: 4