这个问题在这里已有答案:
得到c:/ mingw / bin /../ lib / gcc / mingw32 / 8.2.0 /../../../../ mingw32 / bin / ld.exe:main.o:main.cpp :( .text + 0x2b):在运行G ++ main.o ComplexNumber.o -o输出后使用makefile进行编译时未定义的引用(在ComplexNumber.cpp中插入我的方法)。
我已经尝试在线查看我可能错过的地方,并使用我过去做过的其他头文件作为参考来检查那里的错误,但我没有运气。我在windows上使用cygdrive进行编译,但也尝试在常规命令提示符下使用mingw。
标题文件:'''''''''''
#include <stdio.h>
#ifndef COMPLEXNUMBER_H_
#define COMPLEXNUMBER_H_
template<typename T>
class ComplexNumber
{
public:
// a is a real number, b is a complex number
T a;
T b;
ComplexNumber();
ComplexNumber(T, T);
void toString();
ComplexNumber operator +(ComplexNumber<T>& c);
ComplexNumber operator *(ComplexNumber<T>& c);
bool operator ==(ComplexNumber<T>& c);
};
#endif /* COMPLEXNUMBER_H_ */
''''''''''''''
ComplexNumber.cpp''''''''''''
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include "ComplexNumber.h"
using namespace std;
template <typename T>
ComplexNumber<T>::ComplexNumber()
{}
template <typename T>
ComplexNumber<T>::ComplexNumber(T a, T b)
{
this->a = a;
this->b = b;
}
template <typename T>
ComplexNumber<T> ComplexNumber<T>:: operator +(ComplexNumber& c)
{
ComplexNumber <T> temp;
// adds the complex numbers, (a+bi) + (c+di) = (a+b) + i(c+d)
temp.a = this->a + c.a;
temp.b = this->b + c.b;
return temp;
}
template <typename T>
ComplexNumber<T> ComplexNumber<T>:: operator *(ComplexNumber& c)
{
ComplexNumber<T> temp;
// multiplies complex numbers, (a+bi) + (c+di) = (a*c-b*d) + i(a*d + b*c)
temp.a = (this->a * c.a) - (temp.b * c.b);
temp.b = (temp.a * c.b) + (temp.b * c.a);
return temp;
}
template <typename T>
bool ComplexNumber<T>:: operator ==(ComplexNumber<T>& c)
{
ComplexNumber<T> temp;
// compares complex numbers to see if they're equal, (a+bi) == (c+di) -> if (a==c) & (b==d)
if (temp.a == c.a && temp.b == c.b)
{
cout<< "The complex numbers are equal."<<endl;
return true;
}
return false;
}
template <typename T>
void ComplexNumber<T>::toString()
{
cout<< "("<< this->a<< " + "<< this->b<< "i)"<<endl;
}
MakeFile:''''''''''
all: ComplexNumber
ComplexNumber: main.o ComplexNumber.o
g++ main.o ComplexNumber.o -o output
main.o: main.cpp
g++ -c main.cpp
ComplexNumber.o: ComplexNumber.cpp
g++ -c ComplexNumber.cpp
clean:
rm *.o output
''''''''''''''
@ thej1996,您可以通过两种方式解决它:1)在客户端应用程序中包含Header和cpp文件(ComplexNumber.h / ComplexNumber.cpp)(调用ComplexNumber用法的client.cpp文件)。 2)或者在模板cpp文件(ComplexNumber.cpp)中提供临时函数以避免链接器错误:
void TempFn ()
{
ComplexNumber<int> ComplexObj;
}
无需在任何地方调用此功能。只是为了满足链接器。