#include <iostream>
#include <string>
using namespace std;
int main()
{
class People
{
private:
std::string name;
int age;
string male;
public:
//People(string names, int ages, string males):name(names), age(ages), male(males)//基类中的构造函数
People(string names, int ages, string males)//基类中的构造函数
{
name = names;
age = ages;
male = males;
}
void Print()
{
cout<<"the people name age male = "<<name<<age<<male<<endl;
}
};
class Student:public People{
private:
int score;
public:
Student(string name, int age, string male, int scores):People(name, age, male){ // 派生类中的构造函数
score = scores;
cout<<"the student name age male = "<<name<<age<<male<<"\nscore = "<<score<<endl;
}
void setscore(int score){
score = score;
cout<<"score = "<<score<<endl;
}
};
People person_a("nihao", 9, "female");
person_a.Print();
Student person_stu("fxs", 100, "male", 100);
}
基类的构造函数执行在派生类之前,所以要谨慎使用例如:
#include <iostream>
using namespace std;
class BaseClass{
public:
BaseClass(){
print_it();
}
virtual void print_it() {
cout << "BaseClass print_it" << endl;
}
};
class DerivedClass : public BaseClass {
public:
DerivedClass() {
print_it();
}
virtual void print_it(){
cout << "Derived Class print_it" << endl;
}
};
int main() {
DerivedClass dc;
}
执行结果如下:
BaseClass print_it
Derived Class print_it
继承构造函数 使用using
explicit 可以有效得防止构造函数的隐式转换带来的错误或者误解(按照默认规定,只有一个参数的构造函数也定义了一个隐式转换,将该构造函数对应数据类型的数据转换为该类对象)---------用于一个参数的构造函数中
c++中的虚函数与多态:
纯虚拟函数:
virtual void myfunc ( ) =0;
#include <iostream>
using namespace std;
class A
{
public:
virtual void foo()
{
cout << "A's foo()" << endl;
bar();
}
virtual void bar()
{
cout << "A's bar()" << endl;
}
};
class B: public A
{
public:
void foos()
{
cout << "B's foo()" << endl;
A::foo();
}
void bar()
{
cout << "B's bar()" << endl;
}
};
int main()
{
B bobj;
bobj.foos();
A *p = &bobj;
p->foo();
A aobj = bobj; //转化为A类对象
aobj.foo();
}
还可以参考连接https://www.cnblogs.com/cxq0017/p/6074247.html来学习多态和虚函数
c++的多态性就是通过晚绑定技术来实现的,c++的多态性用一句话概括就是:在基类的函数前加上virtual关键字,在派生类中重写该函数,运行时将会根据对象的实际类型来调用相应的函数,如果对象类型是派生类,就调用派生类的函数,如果对象类型是基类,就调用基类的函数。
下面这个例子也是拷贝上面的连接的,懂了就基本明白函数的多态了
#include <iostream>
#include <stdlib.h>
using namespace std;
class CA
{
public:
void f()
{
cout << "CA f()" << endl;
}
virtual void ff()
{
cout << "CA ff()" << endl;
f();
}
};
class CB : public CA
{
public :
virtual void f()
{
cout << "CB f()" << endl;
}
void ff()
{
cout << "CB ff()" << endl;
f(); //因为ff()是调用的子类里的,所以f()也应该是调用子类里面的
CA::ff();
}
};
class CC : public CB
{
public:
virtual void f()
{
cout << "C f()" << endl;
}
};
int main()
{
CB b;
CA *ap = &b;
CC c;
CB &br = c;
CB *bp = &c;
ap->f();
//CA f()
cout << endl;
b.f();
//CB f()
cout << endl;
br.f();
//C f()
cout << endl;
bp->f();
//C f()
cout << endl;
cout<<"************"<<endl;
ap->ff();
//CB ff()
//CB f()
//CA ff()
//CA f()
cout<<"************"<<endl;
cout << endl;
bp->ff();
//CB ff()
//C f()
//CA ff()
//CA f()
cout << endl;
return 0;
}