开发者

c++ programming problem 2

Hi I'm very new to c++. I just write a c++ code which is following :

#include<iostream>
using namespace std;
class complex
{
 float x,y;
};
int main ()
{
  complex a; 
  a.x=500;
   a.y=600;
cout<<" the value of a.x = "<<a.x<<"\n" ;
cout<<" the value of a.y = "<<a.y<<"\n" ;

return 0;
}

when i compile the program it give me following error:

try.cpp: In function ‘int main()’:
try.cpp:5: error: ‘float complex::x’ is private
try.cpp:10: error: within this context
try.cpp:5: error: ‘float complex::y’ is private
try.cpp:11: error: within this context
try.cpp:5: error: ‘float complex::x’ is private
try.cpp:12: error: within this context
try.cpp:5: error: ‘float complex::y’ is private
try.cpp:13: error: within this context 

i resolve the error by just declaring data member public ;

Now what should i do to make this thing work with private 开发者_StackOverflow社区member? Why can't i access the private member with the object of class? How can i directly access the private data members or why i cant use the data member of class directly with class object ? What's the reason behind it?

How class is implemented in memory? How class prevent us or stop us to use its private data or implements it's security mechanism ? what is compiler do when is saw a class? How compiler implement the class and its security mechanism ?

Please explain this to me


Now what should i do to make this thing work with private member?

If you make them private, then you can write constructor and add other useful functions to your class, to do operations on your complex objects:

class complex
{
   float _x;
   float _y;
   public:
      complex(float x=0.0, float y=0.0) : _x(x), _y(y) {}
                                       //^^^^^^^^^^^^^its initialization list!

      complex operator + (const complex & c)
      {
          return complex(_x + c._x, _y + c._y);
      }
      ostream & print(ostream & out) const
      {
          return out << "(" << _x << ", "<< _y << ")";
      }
      void print() const
      {
          print(cout);
          cout << endl;
      }

      //and so on
};

ostream & operator << (ostream & out, const complex &c)
{
    return c.print(out);
}

Test it:

int main ()
{
  complex a(500,600);
  complex b(80,60);
  complex c = a + b; //operator+() gets invoked!

  a.print();
  b.print();
  c.print();

  cout << "\nprint using cout!" << endl;
  cout << a << endl;
  cout << b << endl;
  cout << c << endl;
  return 0;
}

Output:

(500,600)
(80,60)
(580,660)

print using cout!
(500,600)
(80,60)
(580,660)

See the Online Demo : http://www.ideone.com/TiGat


Your a.x and a.y are trying to access the x and y members from outside the class. If they aren't public, those attempts will fail as you have seen.

If you want the default access to be public instead of private, use struct instead of class.


By default fields you define inside a class are "private" and can only be used by the methods of that class.

You need to define x and y as "public" members of the class.

class complex
{
 public:
 float x,y;
};


public,private and protected are compile time concepts. During runtime, they're not even existent. That cleared up, lets move on to why you can't access private data.

private is just what it says - PRIVATE. And that is total, no access from anywhere but the class itself. A class, by default, is private until specified otherwise.
If you want public by default, take a struct. Other than the default "privacy", they're exactly the same.

struct complex{
  float x;
  float y;
};

Now you can access the members from anywhere.


For further stuff, and from my impression of your questions, it seems you really really need a good C++ book.


Data protection and abstraction are the fundamental concepts of Object Oriented programming. In addition to Mark's Answer, I'd suggest you to read any of your favorite C++ programming books like Eric Nagler's C++, A Hands On Approach or C++ Primer etc.


To access a class's private member, you can:

  1. Providing public methods to read and write the value of private members. In this way, the class can take full control of the access operations.
  2. Providing public methods to return pointers or references of private members. This is not a good way, as the state of object may be destroyed.
  3. Declear classes or functions as friend of the class that contains the private member, so that the friends can access all member. Be sure the friends operate correctly on the class's data member.

The private, protected and public take effect only at compile time, preventing mistaken codes to destory the state of a object. They have no business for runtime security controling.

Let's take an example, see the simple stack class below:

class statck
{
private:
    static const int buffersize = 100;
    int buffer[buffersize];
    int count;
public:
    stack();
    bool Push(int value);
    bool Pop(int value);
    int GetCount();
}

The count memeber logically represent how many value have been pushed into the stack, it's value is managed by Push, Pop and constructor, and should not be changed by code using stack class object, like:

statck s;
s.count = 10;

The code upside is logically meaningless. If the count is public, the code could be compiled, and the mistake was harder to revealed, and by declearing count as private, the mistake is obvious and causes a compiling error.

All the thing access modifiers(public, protected and private) done is to tell compiler, whitch member of a class could appear in some expressions in code other than the class's member method. I didn't use the phrase "access", I think that's what confused you.

The access modifiers won't affect the memory layout produced by compiler to represent the object. Stricly, the layout is depending on compiler and platform's word size, but generally on a 32bit system, the statck object will be a 404 byte long memory block, 400 byte for buffer and 4 byte for count, no matter the buffer and count is public or private. And when the program is running, every code that get the address of the 404 byte memory block can read and write them, the private has nothing to do with this.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜