C++中关键字Struct和Class的区别(3)
/*
** FileName : StructAndClassDiffDemo
** Author : Jelly Young
** Date : 2013/12/7
** Description : More information, please go to http://www.jb51.net
*/
#include <iostream>
using namespace std;
struct A
{
private:
int b;
protected:
int c;
public:
A()
{
b = 10;
c = 20;
d = 30;
}
int d;
};
struct B : A
{
void printA_C()
{
cout<<A::c<<endl;
};
// private member can not see
/*void printA_B()
{
cout<<A::b<<endl;
}*/
void printA_D()
{
cout<<A::d<<endl;
}
};
int main(int argc, char* argv[])
{
A a1;
B b1;
// private member can not see
//cout<<a1.b<<endl;
// protected member can not see
//cout<<a1.c<<endl;
// public member can see
cout<<a1.d<<endl;
return 0;
}
写了这么多了,那么会出现这种一个状况,如果是class的父类是struct关键字描述的,那么默认访问属性是什么?
当出现这种情况时,到底默认是public继承还是private继承,取决于子类而不是基类。class可以继承自struct修饰的类;同时,struct也可以继承自class修饰的类,继承属性如下列描述:
class B:A{}; // private 继承
class A{};
struct B:A{}; // public 继承
最后,那么到底是使用struct,还是使用class呢?这个看个人喜好,但是这里有一个编程规范的问题,当你觉得你要做的更像是一种数据结构的话,那么用struct,如果你要做的更像是一种对象的话,那么用class。
- 上一篇:C++设计模式之组合模式
- 下一篇:C++设计模式之桥接模式