Question for calling function
if i have a class, how can i use the data in the same class function. for example..
class sameclass {public:.... .... private: a[];}; void sameclass::example(int n) { while(n!=0){ cin>>n; a[i]; i++;} } void sameclass::sortTwo(sameclass n1, smaeclass n2) { //how can i use the data in the example function //when i use sameclass s3 = s1.a[]; it said i can't use the pricate member.. } |
Private members should be accessible from member functions of the same class. The following example works fine:
Code:
class classA Also, you might want to use code tags, as they'll preserve your indentation if you're copying and pasting from a text editor. As an aside, if you were trying to access a private member from another class, you would have to write a public accessor function, e.g. Code:
class classA Code:
void classB::someFunc(classA a) |
so if i need to get the private data, i need to use function?
like ClassA s1,s2,s3 s1 and s2 is going to set some num into private data member and s3 use in other function in same class to mix s1 and s2 so i need to write a get function to able to get private date in s1 and s2? am i right? thank |
If all the objects are of the same class and the members you want to access are private then you don't need to use an accessor function - see the first example I gave. Let me explain a bit about what it's doing:
In main(), I create two objects of classA (a1 and a2). I then set the value of a1's member variable, member using the setMember(int) function. Obviously I can't set it directly (i.e. with "a1.member = 3;") because member is private. Next, I call classA's member function, someFunction(classA a) on my object a2 and pass a1 as an argument. That function is again: Code:
void classA::someFunction(classA a) Again, it's only if you're trying to access a private member from a different class (or main or some other function not in a class) that you'll need to use an accessor function (which of course will need to be public so that it can be used). HTH. |
All times are GMT -5. The time now is 07:55 AM. |