#include <iostream.h> class CComplex { public: CComplex(double r = 0, double i = 0) { real = r; imag = i; } int operator int() { return (int)real; } void Display(void) { cout << "(" << real << "," << imag << ")" << endl; } protected: double real; double imag; }; class CVector { public: CVector(CComplex &obj1, CComplex &obj2, CComplex &obj3, CComplex &obj4) { objArray[0] = obj1; objArray[1] = obj2; objArray[2] = obj3; objArray[3] = obj4; } friend CComplex &operator[](CVector obj, int n); private: CComplex objArray[4]; }; CComplex &operator[](CVector obj, int n) { if(n<0 || n>3) { cout<<"Out of range!"<<endl; exit(0); } return obj.objArray[n]; } int main() { CComplex c1(1.1, 1.1); CComplex c2(2.2, 2.2); CComplex c3(3.3, 3.3); CComplex c4(4.4, 4.4); CVector v(c1,c2,c3,c4); v[0].Display(); v[1].Display(); v[2].Display(); v[3].Display(); v[0] = 5.5; ----------------------------------------------------------① v[1] = CComplex(6.6); -------------------------------------------② v[2] = int(CComplex(7.7)); --------------------------------------③ v[3] = int(CComplex(8.8,9.9)); ----------------------------------④ v[0].Display(); v[1].Display(); v[2].Display(); v[3].Display(); return 0; } 问题一:上述程序存在两大错误,在不修改主函数和程序原意的前提下,改正该程序中存在的错误。 问题二:①处的转换属于显式转换还是隐式转换,并解释该转换过程。 问题三:②处的转换属于显式转换还是隐式转换,并解释该转换过程。 问题四:解释③处的转换过程。 问题五:解释④处的转换过程。
时间: 2023-08-15 08:23:24 浏览: 78
问题一:程序中存在两个错误:一是C++标准库头文件应该是<iostream>而不是<iostream.h>;二是CComplex类中的类型转换函数应该是explicit的,因为它可以导致隐式类型转换,可能会引起错误。
修改后的程序如下:
```
#include <iostream>
using namespace std;
class CComplex {
public:
explicit CComplex(double r = 0, double i = 0) {
real = r;
imag = i;
}
int operator int() {
return static_cast<int>(real);
}
void Display(void) {
cout << "(" << real << "," << imag << ")" << endl;
}
protected:
double real;
double imag;
};
class CVector {
public:
CVector(CComplex &obj1, CComplex &obj2, CComplex &obj3, CComplex &obj4) {
objArray[0] = obj1;
objArray[1] = obj2;
objArray[2] = obj3;
objArray[3] = obj4;
}
friend CComplex &operator[](CVector obj, int n);
private:
CComplex objArray[4];
};
CComplex &operator[](CVector obj, int n) {
if(n<0 || n>3) {
cout<<"Out of range!"<<endl;
exit(0);
}
return obj.objArray[n];
}
int main() {
CComplex c1(1.1, 1.1);
CComplex c2(2.2, 2.2);
CComplex c3(3.3, 3.3);
CComplex c4(4.4, 4.4);
CVector v(c1,c2,c3,c4);
v[0].Display();
v[1].Display();
v[2].Display();
v[3].Display();
v[0] = 5.5;
v[1] = CComplex(6.6);
v[2] = static_cast<int>(CComplex(7.7));
v[3] = static_cast<int>(CComplex(8.8,9.9));
v[0].Display();
v[1].Display();
v[2].Display();
v[3].Display();
return 0;
}
```
问题二:①处的转换是显式转换,因为赋值语句右边的5.5是double类型,需要强制转换为CComplex类型才能赋值给v[0]。
问题三:②处的转换是显式转换,因为CComplex(6.6)是一个临时对象,需要将其转换为CComplex类型才能赋值给v[1]。
问题四:③处的转换是显式转换,因为int(CComplex(7.7))需要将CComplex类型的临时对象强制转换为int类型。
问题五:④处的转换是显式转换,因为int(CComplex(8.8,9.9))需要将CComplex类型的临时对象强制转换为int类型。注意,实部8.8是可以转换为int类型的,但虚部9.9无法转换为int类型,因此会截断为整型,即v[3]的实部为8,虚部为0。
阅读全文