【发布时间】:2017-05-19 18:34:45
【问题描述】:
下面的多重继承示例代码不起作用。请问,你能帮忙吗?
子类继承自父类。使用 Child 中的 show() 函数从每个父类中打印出一个对象值。
#include<iostream>
#include<string.h>
using namespace std;
class B
{
protected:
string bname;
public:
B (string bname1)
{bname=bname1;}
string getBName()
{return bname;}
};
class C
{
protected:
string cname;
public:
C (string cname1)
{cname=cname1;}
string getCName()
{return cname;}
};
class A: public B, public C // MultipleInheritance
{
private:
string aname;
public:
A ()
{
cout<<"What is the B name? : " << endl ;
cin >> bname;
cout << "What is the C name? : " << endl;
cin >> cname;
cout <<"What is the A name? : "<< endl ;
cin >> aname;
}
A (string bname1 , string cname1, string aname1)
{bname=bname1; cname=cname1;aname=aname1;}
string getCName()
{return cname;}
};
int main ()
{
A a2 ("parant1","parant2","child1");
cout<<"constructor >>> parent Name 1 : \t"<< a2.getBName()<<"parent Name 2 : "<< a2.getCName()<<" child Name 1: " <<a2.getAName()<<endl;
}
我是初学者。随意编辑问题以使其更简单。
【问题讨论】:
-
不要用
<string.h>,已经过时了,用<string> -
另外,继承的类不能访问其父类的私有元素。将字段
fname和mname设为受保护,以便孩子可以访问它 -
不仅
已过时,而且包含错误!它是 strlen和strcmp之类的 C 头文件,在 C++ 世界中是<cstring>。<string>持有std:string类
标签: c++ class oop inheritance visual-c++