C++中关键字Struct和Class的区别(2)
再让我写代码验证一下: 复制代码 代码如下: /* ** FileName : StructAndClassDiffDemo ** Author : Jelly Young ** Date : 2013/12/7 ** Description : More information, please go to http://
再让我写代码验证一下:
复制代码 代码如下:
/*
** 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
{
int a;
A()
{
a = 10;
}
void print()
{
cout<<"I am from A"<<endl;
}
};
struct B : A
{
int b;
B()
{
a = 30; // set a to 30
b = 20;
}
/*void print()
{
cout<<"I am from B"<<endl;
}*/
};
int main(int argc, char* argv[])
{
B b1;
cout<<b1.a<<endl;
cout<<b1.b<<endl;
b1.print();
A a1;
cout<<a1.a<<endl;
a1.print();
return 0;
}
运行上述代码,struct支持继承。
Struct支持多态么?
写代码测试一下便知:
复制代码 代码如下:
/*
** 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
{
virtual void print() = 0;
};
struct B : A
{
void print()
{
cout<<"I am from B"<<endl;
}
};
struct C : A
{
void print()
{
cout<<"I am from C"<<endl;
}
};
int main(int argc, char* argv[])
{
A *a1;
B *b1 = new B;
C *c1 = new C;
a1 = b1;
a1->print(); // call B, not A
a1 = c1;
a1->print(); // call C, not A
return 0;
}
Struct支持Private、Protected和Public关键字么?
- 上一篇:C++设计模式之组合模式
- 下一篇:C++设计模式之桥接模式
精彩图集
精彩文章