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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
using namespace std;
class Base {
private:
int a;
protected:
int b;
public:
int c;
int getA() { return a; }
int getB() { return b; }
void setA(int a) { this->a = a; }
void setB(int b) { this->b = b; }
void example1() {
cout << a << ", " //a is visible
<< b << ", " //b is visible
<< c << endl; //c is visible
}
};
class Sub : public Base {
public:
void example2() {
// cout << a << ", " //a is hidden
cout << b << ", " //b is visible
<< c << endl; //c is visible
}
};
void example3(Base *base) {
// cout << base->a << ", " //a is hidden
// cout << base->b << ", " //b is hidden
cout << base->c << endl; //c is visible
}
int main() {
Base *x = new Sub,
*y = new Sub,
*z = new Sub;
x->setA( 2 ); //x->a is not public, so we use the appropriate mutator method
x->setB( 3 ); //same thing for x->b
x->c = 5; //x->c is public, so we can access it directly
y->setA( 10 );
y->setB( 20 );
y->c = 30;
z->setA( 1024 );
z->setB( 1048576 );
z->c = 1073741824;
x->example1(); //defined in Base, will display a, b, and c
y->example2(); //defined in Sub, will display only b, and c
example3( z ); //defined as a global function, will display only c
delete x;
delete y;
delete z;
return 0;
}
|
2, 3, 5
20, 30
1073741824 |