继承的知识点(1)

//private:除了本身类内 其余类不可调用
//protected:本身与派生类可以调用
//public:都可以调用
//例程

#include <iostream>
#include <string>
#include <windows.h>
 
using namespace std;
 
class people
{
private:
    string m_name;
    int m_age;
 
 
public:
    void setpeople(string name, int age);
    void showinfo();
};
 
void people::setpeople(string name, int age)
{
    m_name = name;
    m_age = age;
}
 
void people::showinfo()
{
    cout << "名字是:" << m_name << endl;
    cout << "年龄是:" << m_age << endl;
}
 
class student : public people
{
private:
    int m_id;
public:
    void setid(int id);
    void print();
};
 
void student::setid(int id)
{
    m_id = id;
}
 
void student::print()
{
    cout << "学号是:" << m_id << endl;
}
 
int main()
{
    student s1;
    s1.setpeople("tqn", 21);
    s1.setid(202150225);
 
    s1.showinfo();
    s1.print();
 
    system("pause");
    return 0;
}
 

//地址分配上 先分配继承来的 后分配自己声明的

#include <iostream>
 
#include <windows.h>
 
using namespace std;
 
class A
{
public:
    int m_a;
    int m_b;
    A();
    ~A();
};
A::A()
{
    cout << "constuctor A ok~" << endl;
}
 
A::~A()
{
    cout << "destuct A ok~" << endl;
}
 
class B :public A
{
public:
    int m_c;
    B();
    ~B();
};
 
B::B()
{
    cout << "constuctor B ok~" << endl;
}
B::~B()
{
    cout << "destuct B ok~" << endl;
}
 
int main()
{
    B b1;
    cout << &b1.m_a << endl;
    cout << &b1.m_b << endl; 
    cout << &b1.m_c << endl;
    system("pause");
    return 0;
}
 

//初始化的时候 构造的顺序是 父类 --> 成员 --> 自己 这个是语法规定的 没有为什么

#include <iostream>
 
#include <windows.h>
 
using namespace std;
 
class A
{
public:
    int m_a;
    int m_b;
    A(int a);
    ~A();
    void printA();
};
A::A(int a)
{
    cout << "constuctor A ok~" << endl;
    m_a = a;
}
 
A::~A()
{
    cout << "destuct A ok~" << endl;
}
 
void A::printA()
{
    cout << m_a << endl;
}
 
 
class C
{
public:
    int m_c;
    C(int c);
};
 
C::C(int c)
{
    m_c = c;
    cout << "constuctor C ok~" << endl;
}
 
class B :public A
{
public:
    int m_c;
    B(int b);
    ~B();
    void printB();
    C c;
    const int d;
};
 
B::B(int b) : A(b), c(b) , d(b)//初始化列表 这个顺序无所谓
{
    cout << "constuctor B ok~" << endl;
    m_b = b;
}
 
B::~B()
{
    cout << "destuct B ok~" << endl;
}
 
void B::printB()
{
    cout << m_b << endl;
}
 
 
 
int main()
{
    B b1(1);
    b1.printA();
    b1.printB();
 
    system("pause");
    return 0;
}
 

类的继承中 父类子类出现同名成员变量  依然继承 只是调用的时候 调用自己的

#include <iostream>
 
#include <windows.h>
 
using namespace std;
 
class A
{
public:
    int m_a;
    int m_b;
 
};
 
class B :public A
{
public:
    int m_b;
    int m_c;
};
 
 
int main()
{
    B b1;
    cout << sizeof(b1) << endl;
    cout << &b1.m_a << endl;
    cout << &b1.m_b << endl;
    cout << &b1.A::m_b << endl;
    cout << &b1.m_c << endl;
    system("pause");
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/ys5858588/article/details/81268142