- 论坛徽章:
- 0
|
学习C++的时候,想看一下操作符重载,找了网上的一段代码:- //complex.h
- #include <iostream>
- using namespace std;
- class Complex//声明一个复数类
- {
- public:
- Complex(Complex &a);//拷贝构造函数
- Complex(double r=0,double i=0);
- void display();//输出复数的值
- void set(Complex &a);
- Complex plus(Complex a);//复数的加法
- Complex minus(Complex a); //复数的减法
- Complex plus(double r); //复数与实数相加
- Complex minus(double r); //复数与实数相减
- private:
- double real;//复数实部
- double img;//复数虚部
- };
- Complex::Complex(Complex &a)
- {
- real=a.real;
- img=a.img;
- }
- Complex::Complex(double r,double i)
- {
- real=r;
- img=i;
- }
- void Complex::display()
- {
- cout <<real <<(img>=0?"+":"") <<img <<"i";//适合显示1-3i等虚部为负值的复数
- }
- void Complex::set(Complex &a)
- {
- real=a.real;
- img=a.img;
- }
- Complex Complex::plus(Complex a)
- {
- Complex temp(a.real+real,a.img+img);
- return temp;
- }
- Complex Complex::minus(Complex a)
- {
- Complex temp(real-a.real,img-a.img);
- return temp;
- }
- Complex Complex::plus(double r)
- {
- Complex temp(real+r,img);
- return temp;
- }
- Complex Complex::minus(double r)
- {
- Complex temp(real-r,img);
- return temp;
- }
复制代码 然后是cpp文件:- #include "complex.h"
- #include <iostream>
- using namespace std;
- int main()
- {
- Complex a(3,2),b(5,4),temp;
- temp.set(a.plus(b));//temp=a+b
- temp.display();
- cout <<endl;
- temp.set(a.minus(b));//temp=a-b
- temp.display();
- cout <<endl;
- return 0;
- }
复制代码 怎么都在ubuntu下的GCC编译不过去,主要是如下错误:
g++ -Wall -c "complex.cpp" (in directory: /home/oliver/course/c++ for c programmer/code)
complex.cpp: In function ‘int main()’:
complex.cpp:7:22: error: no matching function for call to ‘Complex::set(Complex)’
complex.cpp:7:22: note: candidate is:
In file included from complex.cpp:1:0:
complex.h:33:6: note: void Complex::set(Complex&)
complex.h:33:6: note: no known conversion for argument 1 from ‘Complex’ to ‘Complex&’
complex.cpp:10:23: error: no matching function for call to ‘Complex::set(Complex)’
complex.cpp:10:23: note: candidate is:
In file included from complex.cpp:1:0:
complex.h:33:6: note: void Complex::set(Complex&)
complex.h:33:6: note: no known conversion for argument 1 from ‘Complex’ to ‘Complex&’
Compilation failed.
尝试编译.h文件,得到的报错如下:
gcc -Wall -c "complex.h" (in directory: /home/oliver/course/c++ for c programmer/code)
complex.h:1:20: fatal error: iostream: No such file or directory
compilation terminated.
Compilation failed.
我把.h文件改成.cpp文件,能够编译通过。实在搞不懂什么情况了。求教
|
|