单继承
C++中所谓的继承就是在一个已存在的类基础上建立一个新的类
已存在的类称为基类或父类,新建立的类称为派生类或子类
//单继承--公有派生
#include <iostream>
using namespace std;
class A
{
public:
int z;//公有数据成员
A(int a, int b, int c)
{
cout << "调用类A带参的构造函数" << endl << endl;
x = a;
y = b;
z = c;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
int getz()
{
return z;
}
void print()
{
cout << "x=" << x << ",y=" << y << ",z" << z << endl << endl;
}
protected:
int y;//保护数据成员
private:
int x;//私有数据成员
};
class B : public A
{
public:
B(int a, int b, int c, int d, int e) :A(a, b, c)
{
cout << "调用派生类B带参的构造函数" << endl << endl;
m = d;
n = e;
}
void print()
{
cout << "x=" << getx() << ",y=" << y << ",z" << z <<",m="<<m<<",n="<<n<< endl << endl;//x为基类A的私有成员,在派生类B中不能直接访问
}
int sum()
{
return(getx() + y + z + m + n);
}
private:
int m, n;
};
int main()
{
/*A obj(1, 2, 3);
obj.print();*/
B obj(1, 2, 3, 4, 5);//派生类B创建对象obj,且初始化参数为1,2,3,4,5
obj.print();
cout << "\nsum=" << obj.sum() << endl;
cout << "x=" << obj.getx() << endl;
cout << "y=" << obj.gety() << endl;
cout << "z=" << obj.getz() << endl;
return 0;
}
//单继承--私有派生
//基类中的公有成员和保护成员在派生类中均变成私有的,在派生类中仍可直接使用这些成员,基类中的私有成员,在派生类中不能直接使用
#include <iostream>
using namespace std;
class A
{
public:
int z;//公有数据成员
A(int a, int b, int c)
{
cout << "调用类A带参的构造函数" << endl << endl;
x = a;
y = b;
z = c;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
int getz()
{
return z;
}
void print()
{
cout << "x=" << x << ",y=" << y << ",z" << z << endl << endl;
}
protected:
int y;//保护数据成员
private:
int x;//私有数据成员
};
class B : private A
{
public:
B(int a, int b, int c, int d, int e) :A(a, b, c)
{
cout << "调用派生类B带参的构造函数" << endl << endl;
m = d;
n = e;
}
void print()
{
cout << "x=" << getx() << ",y=" << y << ",z" << z << ",m=" << m << ",n=" << n << endl << endl;//x为基类A的私有成员,在派生类B中不能直接访问
}
int sum()
{
return(getx() + y + z + m + n);
}
private:
int m, n;
};
int main()
{
/*A obj(1, 2, 3);
obj.print();*/
B obj(1, 2, 3, 4, 5);//派生类B创建对象obj,且初始化参数为1,2,3,4,5
obj.print();
cout << "\nsum=" << obj.sum() << endl;
/*cout << "x=" << obj.getx() << endl;私有派生,在外部不能访问
cout << "y=" << obj.gety() << endl;
cout << "z=" << obj.getz() << endl;*/
return 0;
}
//保护派生,基类中的公有成员和保护成员在派生类中均变成保护的和私有的,在派生类中仍可直接使用这些成员,基类中的私有成员,在派生类中不能直接使用
//抽象类:当定义了一个类,只能用作基类来派生出新的类,不能直接用这种类来定义对象
//将类的构造函数或析构函数的访问权限定义为保护时,这种类称为抽象类
#include <iostream>
using namespace std;
class A
{
public:
int x, y;
void print()
{
cout << "x=" << x << ",y=" << y << endl << endl;
}
A()
{
cout << "调用默认的构造函数" << endl;
}
A(int a, int b)
{
cout << "调用类A:带参构造函数" << endl;
x = a;
y = b;
}
};
class B :public A
{
public:
B(int a, int b, int c) :A(a, b)
{
cout << "调用类B:带参构造函数" << endl;
m = c;
}
void print()
{
cout << "x=" << x << ",y=" << y <<",m="<<m<< endl << endl;
}
private:
int m;
A obj;//在派生类中不可以定义A的对象,实际还是类外调用
};
int main()
{
B obj(1, 2, 3);//可以定义派生类对象
obj.print();
return 0;
}