#include<iostream>
using namespace std;
class Base
{int a;
protected:
int b;
public:
Base(int x,int y){a=x;b=y;}
void displayA()
{cout<<a<<endl;}
};
class Derived:public Base
{int d;
public:
Derived(int x,int y,int z)
{d=z;}
void displayB()
{cout<<a;
cout<<b;
cout<<d;}
};
int main()
{Derived t1(10,20,30);
cout<<t1.b<<endl;
t1.displayA();
t1.displayB();}
#include<iostream>
using namespace std;
class Base
{
public:
int a;
int b;
public:
Base(int x, int y)
{
a = x;
b = y; }
void displayA()
{
cout << a << endl;
}
};
class Derived :public Base
{
int d;
public:
Derived(int x, int y, int z):Base(x,y)
{
d = z;
}
void displayB()
{
cout << a;
cout << b;
cout << d;
}
};
int main()
{
Derived t1(10, 20, 30);
cout << t1.b << endl;
t1.displayA();
t1.displayB();
}
公有继承 派生类对象可以访问基类公有成员和保护成员 如果基类的内容不能变该如何修改呢 请大佬指点
原题b是保护成员,可以访问,没问题,但a前面没有指明成员类型的话就会默认为私有成员哟,私有成员是无法直接被外部访问的哟,不管你是何种继承方式。基类内容肯定要改的,你添加友元函数也算是改基类
嗯 谢谢你专业的解答 t1不能访问b 只能访问公有成员 所以删了 a通过公有函数Base::displayA()调用