#include "iostream.h" class CBase { public: CBase(int a) :a(a) { } int a; }; class CDerive1 : public CBase { public: CDerive1(int a) :CBase(a) { } }; class CDerive2 : public CBase { public: CDerive2(int a) :CBase(a) { } }; class CDerive : public CDerive1,public CDerive2 { public: CDerive(int a,int b) :CDerive1(a),CDerive2(b) { } }; void main() { CDerive d(1,2); cout<<d.a<<endl; } 问题一:在不改变原有程序意图的前提下,分别用三种方法改正以上程序,并使程序正确输出。
时间: 2024-03-31 22:37:31 浏览: 66
该程序存在二义性,因为 CDerive 类同时继承了 CDerive1 和 CDerive2,而这两个类都继承自 CBase,因此在 CDerive 中会有两份 CBase 类的成员变量 a,这样在访问 d.a 时就会存在二义性,导致编译错误。
为了解决这个问题,需要通过虚继承来消除二义性。具体实现方法如下:
方法一:使用虚继承
```
#include <iostream.h>
class CBase {
public:
CBase(int a) :a(a) { }
int a;
};
class CDerive1 : virtual public CBase {
public:
CDerive1(int a) :CBase(a) { }
};
class CDerive2 : virtual public CBase {
public:
CDerive2(int a) :CBase(a) { }
};
class CDerive : public CDerive1, public CDerive2 {
public:
CDerive(int a, int b) :CBase(a), CDerive1(a), CDerive2(b) { }
};
void main() {
CDerive d(1, 2);
cout << d.a << endl;
}
```
方法二:将 CDerive1 和 CDerive2 中的 CBase 改为 public 继承
```
#include <iostream.h>
class CBase {
public:
CBase(int a) :a(a) { }
int a;
};
class CDerive1 : public CBase {
public:
CDerive1(int a) :CBase(a) { }
};
class CDerive2 : public CBase {
public:
CDerive2(int a) :CBase(a) { }
};
class CDerive : public CDerive1, public CDerive2 {
public:
CDerive(int a, int b) :CBase(a), CDerive1(a), CDerive2(b) { }
};
void main() {
CDerive d(1, 2);
cout << d.CDerive1::a << endl;
}
```
方法三:在 CDerive 类中定义一个新的成员变量 a,并在构造函数中将 CDerive1 和 CDerive2 中的 a 赋值给这个新变量。
```
#include <iostream.h>
class CBase {
public:
CBase(int a) :a(a) { }
int a;
};
class CDerive1 : public CBase {
public:
CDerive1(int a) :CBase(a) { }
};
class CDerive2 : public CBase {
public:
CDerive2(int a) :CBase(a) { }
};
class CDerive : public CDerive1, public CDerive2 {
public:
CDerive(int a, int b) :CDerive1(a), CDerive2(b), a(a) { }
int a;
};
void main() {
CDerive d(1, 2);
cout << d.a << endl;
}
```
无论使用哪种方法,都可以消除二义性,使程序正确输出。
阅读全文