How to access field of a class by name

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aaa bbb
    New Member
    • Feb 2012
    • 7

    How to access field of a class by name

    Hi guys, I hope you'll help me with this.

    class myCls{
    int x;
    };

    and then I create:

    myCls c1;

    and now:

    is there way that I go like: cout << c1;
    not overloading << operator;
    and it shows me a value of c1.x?
    just wanna replace c1 with that value;
    I need sth smillar to indexer from c#.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    BY default member variables of classes are private.

    You will need to write a member function to return the value so you can display it.

    Code:
    class myCls{
     int x;
       public:
       int Get();
     };
    
    int myCls::Get()
    {
       return x;
    }
    Then in main():

    Code:
    myCls c1;
     
    cout << c1.Get();

    Comment

    Working...