開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
code::blocks
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
問題(Question):
Error message: undefined reference to
code(已經重新寫過):
Complex.h:
#ifndef COMPLEX_H
#define COMPLEX_H
class Complex
{
public:
Complex();//default constructor
Complex(double, double);//constructor
Complex& cadd(Complex&);
Complex& csubtract(Complex&);
Complex& cmultiply(Complex&);
static void print(Complex&);
private:
double real;
double imaginary;
};//end class the_complex
#endif // COMPLEX_H
Complex.cpp:
#include<iostream>
#include"Complex.h"
using namespace std;
the_complex::Complex()//default constructor
{
real = 0;
imagunary = 0;
}
the_complex::Complex(double a,double b)//constructor
{
real = a;
imaginary = b;
}
Complex& the_complex::cadd(const Complex& a)
{
(*this).real += a.real;
(*this).imaginary += a.imaginary;
return *this;
}
Complex& the_complex::csubtract(Complex& a)
{
(*this).real -= a.real;
(*this).imaginary -= a.imaginary;
return *this;
}
Complex& the_complex::cmultiply(Complex& a)
{
(*this).real = a.real * (*this).real - (*this).imaginary * a.imaginary;
(*this).imaginary = a.imaginary * (*this).real + a.real *
(*this).imaginary;
return *this;
}
void the_complex::print(Complex& a)
{
cout<<a.real<<'+'<<a.imaginary<<'i'<<endl;
}
main.cpp:
#include <iostream>
#include "Complex.h"
#include <string>
using namespace std;
int main()
{
double x1, y1, x2, y2;
char s;
Complex result;
x1 = x2 = y1 = y2 = 0;
cout<<"Please enter the real and imaginary number of the first
complex:"<<endl;
cin>>x1>>y1;
Complex e1(x1, y1);
cout<<"Please enter the real and imaginary number of the second
complex:"<<endl;
cin>>x2>>y2;
Complex e2(x2, y2);
cout<<"Please choose an operation: + or - or *"<<endl;
cin>>s;
if (s == '+')
result = e1.cadd(e2);
else if (s == '-')
result = e1.csubtract(e2);
else if (s == '*')
result = e1.cmultiply(e2);
else
{
cout<<"Error input!"<<endl;
return 0;
}
the_complex::print(result);
return 0;
}
已經解決了.......
我沒有用Add files,而是直接新增檔案
所以對軟體來說我沒有把他們放在同一個project底下......
感謝C大和m大回答!!!
作者: matita (pencil) 2015-12-18 07:15:00
header file裡面函數沒加return type 不知道是不是這原因然後程式碼盡量還是貼文字檔會比較好看...
作者: matita (pencil) 2015-12-18 07:51:00
the_complex改成Complex
作者:
Caesar08 (Caesar)
2015-12-18 11:09:00先把新的code貼上來。照你的寫法,print應該要是static
這邊已經是新的code了我有發現一個地方,不知道是不是問題所在就是我的function沒有從object來呼叫,但我是定義在clas裡面。改成把函數(add, multiply...)改為static可解決嗎
作者:
Caesar08 (Caesar)
2015-12-18 12:30:00你的the_complex沒有改成Complex除此之外,.h裡面不要打using namespace std;仔細看了一下你的add、subtract,一種方法是改成static一種方法是operator overloading+friend另外,standard裡面有<complex>,你確定要自己做一個?
作者:
kwpn (ITSST)
2015-12-19 10:49:00幹嘛要一堆(*this),覺得很煩嗎
作者:
BlazarArc (Midnight Sun)
2015-12-19 12:10:00this根本多餘
作者:
IKAFIRE (沒有)
2015-12-19 12:31:00說不定是從C#帶過來的習慣
作者:
uranusjr (â†é€™äººæ˜¯è¶…級笨蛋)
2015-12-19 19:04:00要用 this 不是不行, 但為什麼不用 -> 呢...