Need help with some c++ questions (Total beginner)

Jan 8, 2017 at 11:05pm
Hey guys I've been asked to rewrite this code into the correct form to output x,y and z. But i'm not too sure how to do that? I'm thinking it might be to do with rewriting to make x and y public rather than private and the just adding them to the cout. But that feels too simple.

The second question I have to write a default constructor that initializes x and y to zero.

The third question I have to create an object and display two elements of a pair object.

Thanks for any help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
\\Question 1

  class set
     { 
        private:
         int x, y;
        public:
         int z;
      };
      
      void main()
       {
        set p;
        p.x = 1;
        p.y = 5;
        p.z = 10;
        cout<<p.z<<endl;

\\Question 2
      
       class set
       { 
         int x, y;
         public:
         void input(void)
           { x=1; y=2;}
          void output(void)
           {cout<<x<<y<<endl;}

       };

\\Question 3

 class pair
       { 
         int x, y;
         public:
         void input(int a, int b)
           { x=a; y=b;}
          void output(void)
           {cout<<x<<y<<endl;}

       };
Last edited on Jan 8, 2017 at 11:11pm
Jan 8, 2017 at 11:16pm
You could have accessors/mutators, while keeping member variables private. For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class set
{
public:
    int get_x() const { return x; }
    // etc...

    void set_x( int new_x ) { x = new_x; }
    // etc...

private:
    int x, y, z;
};

int main()
{
    set p;
    p.set_x( 1 ); p.set_y( 5 ); p.set_z( 10 );

    cout << p.get_z() << '\n';
}


You could also overload operator<< to output (x, y, z).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ostream& operator<<( ostream& os, const set& s )
{
    return os << "(" 
            << s.get_x() << ", "
            << s.get_y() << ", " 
            << s.get_z() << ")\n";
}

int main()
{
    set p;
    p.set_x( 1 ); p.set_y( 5 ); p.set_z( 10 );

    cout << p.get_z() << '\n';
    cout << p << '\n';
}
Last edited on Jan 8, 2017 at 11:23pm
Topic archived. No new replies allowed.