#include<iostream> using namespace std; class Complexs{ public: Complexs(double r=0,double i=0):real(r),imag(i){ } void print()const; // 按指定格式输出结果 //**********found********** Complexs operator+(Complexs & c); // 加法运算 //**********found********** friend Complexs& operator*(Complexs c1,Complexs c2); // 乘法运算 private: double real,imag; // 复数的实部和虚部 }; void Complexs::print()const { cout<<real; if(imag<0)cout<<imag<<'i'<<endl; else if(imag>0) cout<<'+'<<imag<<'i'<<endl ; } Complexs Complexs::operator+(Complexs & c) { Complexs t; t.real=real+c.real; t.imag=imag+c.imag; //**********found********** return t; } //**********found********** Complexs operator*(Complexs c1,Complexs c2) { Complexs c; c.real=c1.real*c2.real-c1.imag*c2.imag; //**********found********** c.imag=c1.real*c2.imag+c1.imag*c2.real; return c; } int main() { Complexs z1(2.0,3.0),z2(1.0,-4.0),z; cout<<"z1:"; z1.print(); cout<<"z2:"; z2.print(); z=z1+z2; cout<<"z1+z2:"; z.print(); z=z1*z2; cout<<"z1*z2:"; z.print(); system("pause"); return 0; }错在哪
时间: 2023-07-06 20:42:18 浏览: 31
代码中没有明确指定命名空间,使用了using namespace std;,这是不推荐的做法。应该使用std::来限定标准库的命名空间。
另外,在 Complexs 类的 operator+ 函数中,应该将参数 c 声明为 const Complexs &c,表示不会修改 c 对象的值,提高代码的安全性和效率。
最后,在 operator* 函数中,应该将返回值声明为 Complexs 而不是 Complexs&,因为返回的是一个临时对象,不需要返回一个引用。
修改后的代码如下:
相关问题
#include<iostream> #include<cstdio> using namespace std;是什么意思
#include<iostream> #include<cstdio> using namespace std; 是C++中的预处理指令,用于引入头文件和命名空间。
1. #include<iostream> 是引入iostream头文件,其中包含了输入输出流的定义,例如cout和cin等。
2. #include<cstdio> 是引入cstdio头文件,其中包含了C语言标准输入输出函数的定义,例如printf和scanf等。
3. using namespace std; 是使用std命名空间,std是C++标准库的命名空间,其中包含了很多常用的函数和类。
这些预处理指令的作用是为了在程序中能够使用输入输出流和标准库函数,使得程序更加方便和简洁。
补全程序,并写出程序运行结果。 #include <iostream> using namespace std; class Class { public : Class ( int...
补全程序如下:
```
#include <iostream>
using namespace std;
class Class {
public:
Class(int num) {
cout << "Constructor with one argument called." << endl;
}
Class(int num1, int num2) {
cout << "Constructor with two arguments called." << endl;
}
};
int main() {
Class obj1(10);
Class obj2(20, 30);
return 0;
}
```
程序运行结果为:
```
Constructor with one argument called.
Constructor with two arguments called.
```
解释:
这是一个带有两个构造函数的类`Class`。第一个构造函数接受一个整数参数,第二个构造函数接受两个整数参数。在`main`函数中,我们创建了两个对象`obj1`和`obj2`,分别调用了两个不同的构造函数。所以,程序输出了两个不同的消息。