开发者

How to access member variables, from non member function within class C++

I have created a class called "ShortestTime". I have some functions within it that are not member functions, but I would like them to be able to access my member variables.

ie. I have a function that sorts a List that is a 开发者_如何学编程public member variable, but it doesn't have access to this member variable.

I have read something about "friend" but was unable to get this to work. How do I solve my problem?

Thanks for the help,

Robin


There are ways you could use friend to solve your problem but we would need to see sample code.

But my personal approach would be to add a function to ShortestTime that sorts your private member.

ShortestTime::SortInterals()
{
   //sort private stuff
}

Is there a reason that won't work?


It completely depends on what language we are talking about here. Since you are talking about "friend" functions, I am going to assume you are talking about c++. So basically, a friend function is just a normal function which has access to private and protected members of a class in c++. For example..

int abc(myclass a)    
{   
...   
}   
class myclass   
{   
    int someprivatemembers;   
    public:   
        function myClass() { ... }   
        friend int abc(myclass);   
}

Now, in the above example, the function abc will have access to someprivatemembers of object a passes to it, because it is declared as a "friend" of the class.


I have created a class called "ShortestTime". I have some functions within it that are not member functions, ...

No you don't :-). All the functions within a class are member functions by definition. You might well have some functions without the class - they would not be member functions.

but I would like them to be able to access my member variables. ie. I have a function that sorts a List that is a public member variable, but it doesn't have access to this member variable.

Yes it does. You've said you have a public member variable List:

class X
{
  public:
    List identifier_;
};

All functions have access to the list, irrespective of whether they're member functions or not.

I have read something about "friend" but was unable to get this to work. How do I solve my problem?

The only situation in which you might find you need friend, and hence the one that might apply despite the statements above, is akin to...

class X
{
  public:

  private:
    List identifier_;
};

void some_non_member_function()
{
    X x;
    x.identifier_;  // HOW TO GET ACCESS...?
}

To grant some_non_member_function() access to a private data member, you can...

make it a friend of the class

class X
{
    friend void some_non_member_function();
};

void some_non_member_function()
{
    X x;
    x.identifier_;  // NOW OK
}

make it a member function

class X
{
  public:
    void some_non_member_function()
    {
        X x;
        x.identifier_;  // NOW OK
    }
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜