文件的组织问题
刚刚接触c++,求教:
//complex.h
#ifndef _complex_h_
#define _complex_h_
#include <iostream>
class complex{
public:
complex(){Re=Im=0;}
complex(double r){Re=r;Im=0;}
complex(double r,double i){Re=r;Im=i;}
double getReal(){return Re;}
double getImag(){return Im;}
void setReal(double r){Re=r;}
void setImag(double i){Im=i;}
complex& operator= (complex& ob){Re=ob.Re;Im=ob.Im;}
complex& operator+ (complex& ob);
// friend ostream& operator << (ostream& os,complex& c); //<<
private:
double Re,Im;
};
#endif
//complex.cpp
#include <iostream>
#include <math.h>
#include "complex.h"
complex& complex::operator+ (complex& ob){
complex* result=new complex(Re+ob.Re,Im+ob.Im);
return *result; // (1)此行和上一行为什么要定义complex*定义complex会如何?
}
//main.cpp
#include <iostream>
#include <stdlib.h>
#include "complex.h" //(2) 是否应该为include "complex.cpp"
using namespace std;
int main()
{
double edition=0.001;
cout<<edition<<endl;
complex cp=new complex(); //(3)???
return 0;
}
/*
VC 的错误提示:
Deleting intermediate files and output files for project 'reload - Win32 Debug'.
--------------------Configuration: reload - Win32 Debug------------------Compiling...
complex.cpp
main.cpp
g:\cpp\reload\main.cpp(12) : error C2440: 'initializing' : cannot convert from 'class complex *' to 'class complex'
No constructor could take the source type, or constructor overload resolution was ambiguous
*/
/*Thank You!*/
问题点数:20、回复次数:4Top
1 楼cxq249(cxq249)回复于 2003-12-02 19:54:30 得分 8
(1).应该一样
(2).须包含#include "complex.h"
(3).应该为:complex* cp=new complex();
Top
2 楼z3810(z3810)回复于 2003-12-02 20:04:46 得分 8
你的
complex cp=new complex();
句中cp 对象,而new,出来的是对象的指针,所以报错
应该是
....
complex *cp;
cp = new complex();
......Top
3 楼Drunkard2000(Drunkard2000)回复于 2003-12-02 20:10:22 得分 4
(1)中的*result 改为result
返回一个指针Top
4 楼zhuangzhou(当时间也被挥霍一空,我还会有什么?)回复于 2003-12-02 20:17:14 得分 0
Ok
It is different form Java!Top




