0
点赞
收藏
分享

微信扫一扫

基类指针保存派生类对象,基类指针只能访问基类里成员(7)

兮城 2022-07-13 阅读 62


#ifndef
#define
class A {
public:
int a;
int b;
A();

};

#endif

#include "A.h"
#include <iostream>
using namespace std;

A::A():a(1),b(2) {
cout << "a = " << a << "b= " << b << endl;
}

#ifndef
#define
#include "A.h"
class B:public A {
public:
B();
int c;
int d;

};

#endif

#include "B.h"
#include "A.h"
#include <iostream>
using namespace std;


B::B() :c(3), d(4) {
cout << "c= " << c << "d= " << d << endl;
}

#include "A.h"
#include "B.h"

int main() {


B b1;
A *a1 = &b1;//基类指针或引用保存派生类对象,指针能访问的只有基类里的内容
a1->a;
a1->b;
//a1->c; 错

b1.a;
b1.a;
b1.c;
b1.d;


return 0;
}


举报

相关推荐

0 条评论