0
How to access the data prsnt in private??
5 Respuestas
+ 12
Make member functions inside the class with public access to get and set the private part's variable values...
Or you may use friend functions to allow the particular function to access the private data variables...
Eg:
class Example
{
private:
int data;
public:
int get()
{return data;}
void set(int d)
{data=d;}
friend int view()
{return data;}
};
int main(void)
{
Example ex;
ex.set(2);
int c=ex.get();
int d=view();
cout<<c<<d;
//Prints 22, as both c and d are 2.
}
+ 1
using friend function
+ 1
Most of the time, you need to be a friend to get into someone's privates.
+ 1
using some other functions (methods) in public section
example :
#include <iostream>
#include <string>
using namespace std;
class car {
private:
long price = 25000;
public:
void showPrice() {
cout << price << endl;
}
};
int main() {
car BMW;
BMW.showPrice(); // outputs 25000
return 0;
}
0
tq