1.C++继承经典例子

 #include <iostream>
using namespace std;
class Base
{
private:
int b_number;
public:
Base(){}
Base(int i) : b_number(i) { }
int get_number() { return b_number; }
void print() { cout << b_number << endl; }
}; class Derived : public Base
{
private:
int d_number;
public:
// constructor, initializer used to initialize the base part of a Derived object.
Derived(int i, int j) : Base(i), d_number(j) { };
// a new member function that overrides the print( ) function in Base
void print()
{
cout << get_number() << " ";
// access number through get_number( )
cout << d_number << endl;
}
};
int main()
{
Base a();
Derived b(, );
cout << "a is ";
a.print(); // print( ) in Base
cout << "b is ";
b.print(); // print( ) in Derived
cout << "base part of b is ";
b.Base::print(); // print( ) in Base
return ;
}

2.

 #include <iostream>
#include <cmath>
using namespace std; class Point
{
private:
double x;
double y;
public:
Point(double i, double j) : x(i), y(j) { }
void print() const
{
cout << "(" << x << ", " << y << ")";
}
}; class Figure
{
private:
Point center;
public:
Figure(double i = , double j = ) : center(i, j) { } Point& location()
{
return center;
} // return an lvalue
void move(Point p)
{
center = p;
draw();
}
virtual void draw() = ; // draw the figure
virtual void rotate(double) = ;
// rotate the figure by an angle
}; class Circle : public Figure
{
private:
double radius;
public:
Circle(double i = , double j = , double r = ) : Figure(i, j), radius(r) { }
void draw()
{
cout << "A circle with center ";
location().print();
cout << " and radius " << radius << endl;
}
void rotate(double)
{
cout << "no effect./n";
} // must be defined
}; class Square : public Figure
{
private:
double side; // length of the side
double angle; // the angle between a side and the x-axis
public:
Square(double i = , double j = , double d = , double a = ) : Figure(i, j), side(d), angle(a) { }
void draw()
{
cout << "A square with center ";
location().print();
cout << " side length " << side << ".\n"
<< "The angle between one side and the X-axis is " << angle << endl;
}
void rotate(double a)
{
angle += a;
cout << "The angle between one side and the X-axis is " << angle << endl;
}
void vertices()
{
cout << "The vertices of the square are:\n";
// calculate coordinates of the vertices of the square
}
}; int main()
{
Circle c(, , );
Square s(, , );
Figure *f = &c, &g = s;//f是指针,g是引用。
f->draw();
f->move(Point(, ));
g.draw();
g.rotate(); s.vertices();
// Cannot use g here since vertices( ) is not a member of Figure. 注意!!!!!!
//(g是Figure类型的,而vertices是Square派生类特有的。所以通过Figure类型的对象访问不到vertices)
return ;
}

3.1 没有虚析构函数,继承类没有析构

 #include <iostream>
#include <string>
using namespace std; class Thing
{
public:
virtual void what_Am_I() { cout << "I am a Thing.\n"; }
~Thing(){ cout << "Thing destructor" << endl; }
};
class Animal : public Thing
{
public:
virtual void what_Am_I() { cout << "I am an Animal.\n"; }
~Animal(){ cout << "Animal destructor" << endl; }
}; int main()
{
Thing *t = new Thing;
Animal*x = new Animal;
Thing* array[];
array[] = t; // base pointer
array[] = x;
for (int i = ; i<; i++)
array[i]->what_Am_I();
delete array[];
delete array[];
return ;
}

3.2.

 #include <iostream>
#include <string>
using namespace std; class Thing
{
public:
virtual void what_Am_I() { cout << "I am a Thing.\n"; }
~Thing(){ cout << "Thing destructor" << endl; }
}; class Animal : public Thing
{
public:
virtual void what_Am_I() { cout << "I am an Animal.\n"; }
~Animal(){ cout << "Animal destructor" << endl; }
}; void main()
{
Thing t;
Animal x;
Thing* array[];
array[] = &t; // base pointer
array[] = &x;
for (int i = ; i<; i++) array[i]->what_Am_I();
return;
}

与上面的3.1对比。两个程序只有main函数不一样。原因大概是3.1中定义的是指针,如Thing* t=new Thing。而3.2中定义的是对象,如Thing t。对象消亡时会自动调用析构函数。指针的话需要自己去delete。所以做项目时最好用智能指针,因为能自动垃圾回收。

4.多继承

 #include <iostream>
using namespace std; class A
{
private:
int a;
public:
A(int i) : a(i) { }
virtual void print() { cout << "a: " << a << endl; }
int get_a() { return a; }
}; class B
{
private:
int b;
public:
B(int j) : b(j) { }
void print() { cout << "b: " << b << endl; }
int get_b() { return b; }
}; class C : public A, public B
{
int c;
public:
C(int i, int j, int k) : A(i), B(j), c(k) { }
void print()
{
cout << "c_print begin" << endl;
A::print(); B::print();
cout << "c: " << c << endl;
cout << "c_print end" << endl;
}
// use print( ) with scope resolution
void get_ab() { cout << "c-get_ab: " << get_a() << " " << get_b() << endl; }
// use get_a( ) and get_b( ) without scope resolution
}; int main()
{
C x(, , );
A* ap = &x;
B* bp = &x;
ap->print(); // use C::print( );
bp->print(); // use B::print( );
// bp -> A::print( ); // as if x is inherited from B only,
// cannot access A::print( );
x.A::print(); // use A::print( );
x.get_ab();
return ;
}

5.共同基类的多继承

 #include <iostream>
using namespace std; class R
{
int r;
public:
R(int anInt){ r = anInt; };
void printOn(){ cout << "r=" << r << endl; };
}; class A : public R
{
int a;
public:
A(int int1, int int2) :R(int2){ a = int1; };
}; class B : public R
{
int b;
public:
B(int int1, int int2) :R(int2){ b = int1; };
}; class C : public A, public B
{
int c;
public:
C(int int1, int int2, int int3) :A(int2, int3), B(int2, int3){ c = int1; }
}; int main()
{
int i;
R rr();
A aa(, );
B bb(, );
C cc(, , );
rr.printOn();
aa.printOn(); //inherits R printOn
bb.printOn(); //inherits R printOn
//cc.printOn(); //would give error
return ;
}

6.虚基类

 #include <iostream>
using namespace std; class R
{
int r;
public:
R(int x = ) : r(x) { } // constructor in R
void f(){ cout << "r=" << r << endl; }
void printOn(){ cout << "printOn R=" << r << endl; }
}; class A : public virtual R
{
int a;
public:
A(int x, int y) : R(x), a(y) { } // constructor in A
void f(){ cout << "a=" << a << endl; R::f(); }
}; class B : public virtual R
{
int b;
public:
B(int x, int z) : R(x), b(z) { }// constructor in B
void f(){ cout << "b=" << b << endl; R::f(); }
}; class C : public A, public B
{
int c;
public:
// constructor in C, which constructs an R object first
C(int x, int y, int z, int w) : R(x), A(x, y), B(x, z), c(w) { }
void f(){ cout << "c=" << c << endl; A::f(); B::f(); }
}; int main()
{
R rr();
A aa(, );
B bb(, );
C cc(, , , );
cc.printOn(); //uses R printOn but only 1 R..no ambiguity
cc.f(); // shows multiple call of the R::f()
return ;
}

7.

 #include <iostream>
using namespace std; class R
{
int r;
public:
R(int x = ) : r(x) { } // constructor in R
void f(){ cout << "r=" << r << endl; }
}; class A : virtual public R
{
int a;
protected:
void fA(){ cout << "a=" << a << endl; };
public:
A(int x, int y) : R(x), a(y) { } // constructor in A
void f() { fA(); R::f(); }
}; class B : virtual public R
{
int b;
protected:
void fB(){ cout << "b=" << b << endl; };
public:
B(int x, int y) : R(x), b(y) { } // constructor in A
void f() { fB(); R::f(); }
}; class C : public A, public B
{
int c;
protected:
void fC(){ cout << "c=" << c << endl; };
public:
C(int x, int y, int z, int w) : R(x), A(x, y), B(x, z), c(w) { }
void f()
{
R::f(); // acts on R stuff only
A::fA(); //acts on A stuff only
B::fB(); // acts on B stuff only
fC(); // acts on C stuff only
}
}; void main()
{
R rr();
A aa(, );
B bb(, );
C cc(, , , );
cc.f();
}

8.私有继承

 #include <iostream>
using namespace std; class Base
{
private:
int priv;
protected:
int prot;
int get_priv() { return priv; }
public:
int publ;
Base();
Base(int a, int b, int c) : priv(a), prot(b), publ(c) { }
int get_prot() { return prot; }
int get_publ() { return publ; }
}; class Derived1 : private Base // private inheritance
{
public:
Derived1(int a, int b, int c) : Base(a, b, c) { }
int get1_priv() { return get_priv(); }
// priv not accessible directly
int get1_prot() { return prot; }
int get1_publ() { return publ; }
}; class Leaf1 : public Derived1
{
public:
Leaf1(int a, int b, int c) : Derived1(a, b, c) { }
void print()
{
cout << "Leaf1 members: " << get1_priv() << " "
// << get_priv( ) // not accessible
<< get1_prot() << " "
// << get_prot( ) // not accessible
// << publ // not accessible
<< get1_publ() << endl;
} // data members not accessible. get_ functions in Base not accessible
}; class Derived2 : protected Base // protected inheritance
{
public:
Derived2(int a, int b, int c) : Base(a, b, c) { }
}; class Leaf2 : public Derived2
{
public:
Leaf2(int a, int b, int c) : Derived2(a, b, c) { }
void print()
{
cout << "Leaf2 members: " << get_priv() << " "
// << priv // not accessible
<< prot << " "
<< publ << endl;
} // public and protected data members accessible. get_ functions in Base accessible.
}; class Derived3 : public Base // public inheritance
{
public:
Derived3(int a, int b, int c) : Base(a, b, c) { }
}; class Leaf3 : public Derived3
{
public:
Leaf3(int a, int b, int c) : Derived3(a, b, c) { }
void print()
{
cout << "Leaf3 members: " << get_priv() << " "
<< prot << " "
<< publ << endl;
} // public and protected data members accessible. get_ functions in Base accessible
}; int main()
{
Derived1 d1(, , );
Derived2 d2(, , );
Derived3 d3(, , );
// cout << d1.publ; // not accessible
// cout << d1.get_priv( ); // not accessible
// cout << d2.publ; // not accessible
// cout << d2.get_priv( ); // not accessible
cout << d3.publ; // OK
cout << d3.get_prot(); // OK
Leaf1 lf1(, , );
Leaf2 lf2(, , );
Leaf3 lf3(, , );
// cout << lf1.publ << endl; // not accessible
// cout << lf2.publ << endl; // not accessible
cout << lf3.publ << endl; // OK
return ;
}

total:


 多级继承
// Point-Circle-Cylinder
#include <iostream.h>
// THE POINT CLASS
class Point
{
friend ostream & operator<<(ostream &,Point &);
public: // constructor
Point (double xval =, double yval= )
{ x=xval; y=yval;};
protected: // accessed by derived class
double x;
double y;
};
ostream & operator << (ostream & os,
Point & apoint)
{
cout <<" Point:X:Y: "<<apoint.x << ","
<< apoint.y<< "/n";
return os;
}
//The Circle class inherits from class Point
class Circle : public Point
{
friend ostream & operator<<(ostream &,Circle&);
public:
Circle (double r=,double xval=,double yval=)
:Point(xval,yval), radius(r)
{
//radius = r;
}
double area()
{
return (3.14159* radius *radius);
}
protected:
double radius;
}; //note casting circle to point
ostream & operator <<(ostream & os, Circle & aCircle)
{
cout<< "Circle:radius:" << aCircle.radius;
os<< aCircle.x << "/n";
os<< aCircle.y << "/n";
return os;
}
// THE CYLINDER CLASS
class Cylinder : public Circle
{
friend ostream & operator << (ostream & ,Cylinder &);
public:
Cylinder (double hv=,double rv=,
double xv=,double yv= )
: Circle( xv,yv,rv)
{
height = hv;
}
double area ( );
protected: // may have derived classes
double height;
};
double Cylinder :: area ( )
{ // Note that cylinder area uses Circle area
return 2.0* Circle::area() + 2.0*3.14159* radius*height;
}
ostream & operator << (ostream & os,
Cylinder & acylinder)
{
cout << "cylinder dimensions: ";
cout << "x: " <<acylinder.x;
cout << " y: " <<acylinder.y ;
cout << " radius: " <<acylinder.radius ;
cout << " height: " <<acylinder.height
<< endl;
return os;
}
int main(void)
{
Point p(,);
Circle c(,,);
Cylinder cyl(,,,);
cout << p;
cout << c;
cout << "area of cirle:" << c.area() << endl;
cout<< cyl;
cout<<"area of cylinder:"<< cyl.area()<<endl ;
cout<<"area of cylinder base is "
<< cyl.Circle::area() << endl;
return ;
} protected 访问控制属性在继承的意义 //Example of treating derived class object as base class objects. Point------Circle
#include <iostream.h>
// THE POINT CLASS
class Point
{
friend ostream & operator<<(ostream &,Circle&);
public:
Point (double xval =, double yval= ) { x=xval; y=yval;};
public:
void print()
{
cout <<" Point:X:Y: "<<x << "," <<y<< "/n";
}
protected: // accessed by derived class
double x; double y;
};
ostream & operator << (ostream & os, Point & apoint)
{
cout <<" Point:X:Y: "<<apoint.x << ","<< apoint.y<< "/n";
return os;
} //The Circle class inherits from class Point
class Circle : public Point
{
friend ostream & operator<<(ostream &,Circle&);
public:
Circle (double r=,double xval=,double yval=):Point(xval,yval)
{ radius = r;};
void print()
{
cout<< "Circle:radius:" <<radius<<endl;
cout <<" Point:X:Y: "<<x << "," <<y<< "/n";
}
double area()
{ return (3.14159* radius *radius);};
protected:
double radius;
};
//note casting circle to point
ostream & operator <<(ostream & os, Circle & aCircle)
{
cout<< "Circle:radius:" << aCircle.radius;
cout<< (Point) aCircle << "/n";
return os;
} //We will look at a few main programs based on previous class definitions. Casting and assignments
void main (void )
{
Point p(,); cout <<"Point P= "<< p;
Point pp(,); cout <<"Point PP= "<< pp;
Circle c(,,); cout <<"Circle c= "<< c; //radius =7
pp = p; cout <<"Point PP= "<< pp; //built in assign =
// a circle is a member of the point class so assign a circle to a point.
pp = c; //legal; also assignment O.K.
cout <<"Point PP= "<< pp;
pp= (Point) c; // but better use the cast
cout <<"Point PP= "<< pp; //note we get only the point part of the Circle
//c = (Circle) pp; // illegal Cannot convert 'class Point' to 'class Circle'
//c=pp; //illegal assignment not defined
Point* p;
p = &c;
P->print(); //call base class print
((Circle*)p)->print();
Point& r = c;
r.print();
((Circle&)r).print();
} 类的兼容性规则 #include <iostream.h>
class Base
{
public:
void func( )
{cout << "Base class function./n";}
};
class Derived : public Base
{
public:
void func( )
{cout << "Derived class function./n";}
};
void foo(Base b)
{ b.func( ); }
int main( )
{
Derived d;
Base b;
Base * p = &d;
Base& br = d;
b = d;
b.func( );
d.func( );
p -> func( );
foo(d);
br.func( );
return ;
} 虚析构函数,防止内存泄露 #include <iostream.h>
#include <string.h>
class Base
{
protected:
int id;
char * name;
public:
// default constructor
Base(int a = , char * s = "") : id(a)
{
if (!s)
{
name = NULL;
}
else
{
name = new char[strlen(s) + ];
strcpy(name, s);
}
cout << "base default constructor/n";
}
// copy constructor
Base(const Base& b) : id(b.id)
{
if (!b.name) { name = NULL; }
else
{
name = new char[strlen(b.name) + ];
strcpy(name, b.name);
}
cout << "base copy constructor/n";
}
// destructor
~Base( )
{
if( name != NULL ) delete [ ] name;
cout << "base destructor/n";
}
const Base& operator= (const Base& b);
friend ostream& operator << (ostream&, const Base&);
};
const Base& Base:perator= (const Base& b)
{
if (this != &b) // Check if an object is assigned to itself.
{
id = b.id;
delete [ ] name; // Destroy the old object.
if (!b.name) { name = NULL; }
else
{
name = new char[strlen(b.name) + ];
strcpy(name, b.name);
}
}
cout << "base assignment operator/n";
return *this;
}
ostream& operator << (ostream& out, const Base& b)
{
out << "Base member id = " << b.id << endl;
out << "Base member name = " << b.name << endl; return out;
}
class Derived : public Base
{
private:
float f;
char * label;
public:
// default constructor
Derived(int a = , char * s = "", float x = , char * t = "") : Base(a, s), f(x)
{
if (!t) { label = NULL; }
else
{
label = new char [strlen(t) + ];
strcpy(label, t);
}
cout << "derived default constructor/n";
}
// copy constructor
Derived(const Derived& d) : Base(d), f(d.f)
// d used as an instance of Base
{
if(!d.label) { label = NULL; }
else
{
label = new char [strlen(d.label) + ];
strcpy(label, d.label);
}
cout << "derived copy constructor/n";
}
// destructor
~Derived( )
{
delete [ ] label;
cout << "derived destructor/n";
}
const Derived& operator= (const Derived& d);
friend ostream& operator << (ostream&, const Derived&);
};
const Derived& Derived:perator= (const Derived& d)
{
if (this != &d)
{
delete [ ] label;
Base:perator=(d); // Assign the Base part of d to the Base
// part of the object that calls this operator;
f = d.f;
if (!d.label) { label = NULL; }
else
{
label = new char [strlen(d.label) + ];
strcpy(label, d.label);
}
cout << "derived assignment operator/n";
}
return *this;
}
ostream& operator << (ostream& out, const Derived& d)
{
out << (Base)d; // Convert d to Base object to output Base members.
out << "Derived member f = " << d.f << endl;
out << "Derived member label = " << d.label << endl;
return out;
}
int main( )
{
Derived d1;
Derived d2(d1);
return ;
}

http://blog.csdn.net/zhaori/article/details/1700356

C++ inheritance examples的更多相关文章

  1. Java Annotation 机制源码分析与使用

    1 Annotation 1.1 Annotation 概念及作用      1.  概念 An annotation is a form of metadata, that can be added ...

  2. Think Python - Chapter 18 - Inheritance

    In this chapter I present classes to represent playing cards, decks of cards, and poker hands.If you ...

  3. Classical Inheritance in JavaScript

    JavaScript is a class-free, object-oriented language, and as such, it uses prototypal inheritance in ...

  4. Design Pattern in Simple Examples

    Instead of defining what is design pattern lets define what we mean by design and what we mean by pa ...

  5. Public Private Protect Inheritance and access specifiers

    In the previous lessons on inheritance, we've been making all of our data members public in order to ...

  6. 10 Things ASP.NET Developers Should Know About Web.config Inheritance and Overrides(转)

    10 Things ASP.NET Developers Should Know About Web.config Inheritance and Overrides Wednesday, Janua ...

  7. Composition or inheritance for delegating page methods?

    引用链接:http://watirmelon.com/2011/01/24/composition-or-inheritance-for-delegating-page-methods/ Compos ...

  8. Inheritance and subclassing in Go - or its near likeness

    原文: http://golangtutorials.blogspot.com/2011/06/inheritance-and-subclassing-in-go-or.html ---------- ...

  9. ODB Examples

    http://www.codesynthesis.com/products/odb/examples.xhtml The following list gives an overview of the ...

随机推荐

  1. vue 路由传参 、接收参数

    传参组件 一. <router-link :to='"/main/course?navName=" +item.columnName + "&id=&quo ...

  2. <asp:FileUpload>控件 获取不到文件名

    <asp:FileUpload>控件 放在了<asp:UpdatePanel>控件中会导致获取不到文件名.

  3. DataAdapter对象

    DataAdapter对象在物理数据库表和内存数据表(结果集)之间起着桥梁的作用.它通常与DataTable对象或DataSet对象配合来实现对数据库的操作. DataAdapter对象是一个双向通道 ...

  4. 我的Python升级打怪之路【一】:python的简单认识

    Python的简介 Python与其他语言的对比: C和Python.Java.C# C语言:代码直接编译成了机器码,在处理器上直接执行 Python.Java.C#:编译得到相应的字节码,虚拟机执行 ...

  5. 【C语言】-返回指针的函数与指向函数的指针

    本文目录 前言 一.返回指针的函数 二.指向函数的指针 说明:这个C语言专题,是学习iOS开发的前奏.也为了让有面向对象语言开发经验的程序员,能够快速上手C语言.如果你还没有编程经验,或者对C语言.i ...

  6. PHP多维数据排序(不区分大小字母)

    1. PHP中最普通的数组排序方法 sort(); 看个例子: <?php $test = array(); $test[] = 'ABCD'; $test[] = 'aaaa'; $test[ ...

  7. js 验证字符串是否全为中文

    js 验证字符串是否全为中文: function isChinese(str) { var reg = /^[\u4E00-\u9FA5]+$/; if(reg.test(str)){ return ...

  8. WAMP环境配置-PHP安装

    我这次环境配置安装的是php-5.6.25版本! (最近我在反复安装PHP的时候出现了一个问题,httpd.conf加载php5apache2_4.dll出现错误,怎么修改都不行,此时我安装的是VC1 ...

  9. JDK12 concurrenthashmap源码阅读

           本文部分照片和代码分析来自文末参考资料        java8中的concurrenthashmap的方法逻辑和注解有些问题,建议看最新的JDK版本        建议阅读 concu ...

  10. java设计模式--基础思想总结--抽象类与架构设计思想

    抽象类?这个东西我感觉没什么卵用啊,又不能拿来new对象,没有具体的对象的抽象类,有什么实际的意义呢?这是很多刚刚接触java抽象类语法时的第一反应(当然,包括我).确实,很多刚刚接触抽象类这个概念的 ...