基本语法
#include <iostream>
#include <string>
using namespace std;
//语法:子类类名:public 父类类名
class Animal
{
public:
Animal() {};
void walk(string args) {
cout << args <<" is walking" << endl;
}
};
class Dog:public Animal
{
public:
Dog() {
name = "dog";
}
string name;
};
class Cat:public Animal
{
public:
Cat() {
name = "cat";
}
string name;
};
int main() {
Dog d;
d.walk(d.name);
Cat c;
c.walk(c.name);
return 0;
}
继承方式
#include <iostream>
#include <string>
using namespace std;
//private。public。protected继承
/*
公有继承(public):当一个类派生自公有基类时,基类的公有成员也是派生类的公有成员,基类的保护成员也是派生类的保护成员,基类的私有成员不能直接被派生类访问,但是可以通过调用基类的公有和保护成员来访问。
保护继承(protected): 当一个类派生自保护基类时,基类的公有和保护成员将成为派生类的保护成员。
私有继承(private):当一个类派生自私有基类时,基类的公有和保护成员将成为派生类的私有成员。
继承方式/基类成员 public成员 protected成员 private成员
public继承 public protected 不可见
protected继承 protected protected 不可见
private继承 private private 不可见
*/
//1.public
class Dad {
public:
int a = 11;
protected:
int b = 22;
private:
int c = 33;
};
class Son :public Dad{
public:
};
class Son2 :protected Dad {
public:
};
class Son3 :private Dad {
public:
};
int main() {
return 0;
}
多继承
#include <iostream>
#include <string>
using namespace std;
class GrandFather{
public:
int gargs = 11;
};
class Father:public GrandFather{
public:
int fargs = 22;
};
class Son:public GrandFather,public Father{
public:
int s1 = 5;
int s2 = 6;
};
int main() {
Son son;
cout << sizeof(son) << endl;//20个字节
return 0;
}
构造与析构顺序/属性继承访问
#include <iostream>
using namespace std;
//1.构造解析顺序;
//2.父类子类属性与方法同名访问办法;
//3.静态属性访问办法;
class Base {
public:
Base() {cout << "Base in Base" << endl;};
~Base() { cout << "~Base in Base" << endl; }
int a = 20;
void func() { cout << "Base func" << endl; }
static int static_b;
};
int Base::static_b = 33;
class Son:public Base {
public:
Son() { cout << "Son in Son" << endl; };
~Son() { cout << "~Son in Son" << endl; }
int a = 33;
void func() { cout << "Son func" << endl; }
static int static_b;
};
int Son::static_b = 66;
int main() {
Son s;
cout << s.a << endl;
cout << s.Base::a << endl;//2.1通过+作用域才能访问父类的属性。
s.func();
s.Base::func();//2.2通过+作用域才能访问父类的方法。
//3.1通过对象访问
cout << s.static_b << endl;
cout << s.Base::static_b << endl;
//3.2通过类名访问
cout << "''':"<<Son::Base::static_b << endl;
cout << "''':" << Son::static_b << endl;
return 0;
}
/*
顺序:
Base in Base
Son in Son
~Son in Son
~Base in Base
*/
#include <iostream>#include <string>using namespace std;
//语法:子类类名:public 父类类名
class Animal{public:Animal() {};void walk(string args) {cout << args <<" is walking" << endl;}};
class Dog:public Animal{public:Dog() {name = "dog";}string name;};
class Cat:public Animal{public:Cat() {name = "cat";}string name;};
int main() { Dog d;d.walk(d.name);
Cat c;c.walk(c.name);
return 0;}