private,public,protected
protected:在类的内部使用和在继承的子类中使用。
public继承:父类成员在子类中保持原有访问级别
#include
using namespace std;
class Test {
public: //
int a;
protected:
int b;
private:
int c;
public:
void print1()
{
cout << “a” <<endl;
}
};
class Child:public Test
{
public:
void users()
{
a = 1;
b = 1;
//c = 2; // 私有成员不能被使用。
}
private:
};
int main()
{
Child c1;
c1.a;
//c1.b; err
//c1.c;
system(“pause”);
return 1;
}
private继承:父类成员在子类中变为private成员
例子:
#include <iostream>
using namespace std;
class Test {
public: //
int a; //老爹的名字
protected:
int b; // lao die 银行卡密码
private:
int c; //情人。
public:
void print1()
{
cout << "a" <<endl;
}
};
class Child:private Test
{
public:
void users()
{
a = 1;
b = 1;// 可以继承银行卡密码。遗产私有的继承私有的,在类内可以访问,类外不可以访问。
//c = 2; // 私有成员不能被使用。
}
private:
};
int main()
{
Child c1; //a b c 都不能被访问。
system("pause");
return 1;
}
protected继承:父类中public成员会变成protected
父类中public成员会变成protected
父类中protected成员仍然为protected
父类中private成员仍然为private
例子:
#include
using namespace std;
class Test {
public: //
int a; //老爹的名字
protected:
int b; // lao die 银行卡密码
private:
int c; //情人。
public:
void print1()
{
cout << “a” <<endl;
}
};
class Child:protected Test
{
public:
void users()
{
a = 1; // OK
b = 1;// 在子类内部可以被使用。
// c = 2; // 在类内和外部都不能被使用。
}
private:
};
int main()
{
Child c1;
//c1.a = 10; //err
/// c1.b = 20; //err
//c1.c = 30; //eerr
system(“pause”);
return 1;
}
C++中子类对外访问属性表
1、见到protected关键字,第一反映是,在自己的家族中使用。
综合练习:
#include
#include
using namespace std;
class A
{
private:
int a;
protected:
int b;
public:
int c;
A()
{
a = 0;
b = 0;
c = 0;
}
void set(int a, int b, int c)
{
this->a = a;
this->b = b;
this->c = c;
}
};
class B : public A
{
public:
void print()
{
//cout<<"a = "<<a; //err a是错的,私有的在何种情况下都不能被访问。
cout << "b = " << b;// b是保护类型的,在类内可以被访问。
cout << "c = " << endl;
}
};
class C : protected A
{
public:
void print()
{
//cout<<"a = "<<a; //err 私有。
cout << "b = " << b;// 保护的通过保护的方式,在类内使用。
cout << "c = " <<c<< endl; // c是保护的。
}
};
class D : private A
{
public:
void print()
{
//cout<<"a = "<<a; //
cout << "b = " << b << endl; // 私有的继承方式,在类的内部可以被使用。
cout << "c = " << c << endl; // ckeyi
}
};
int main_01(int argc, char *argv[])
{
A aa;
B bb;
C cc;
D dd;
aa.c = 100; //ok
bb.c = 100; //ok
aa.set(1, 2, 3);
bb.set(10, 20, 30);
bb.print();
cc.print();
dd.print();
system("pause");
return 0;
}
输出结果:
b = 20c =
b = 0c = 0
b = 0
c = 0
请按任意键继续. . .