我试图在c++中为3-D vector 创建一个类,但是存在一些错误。我以前在python中学过一点oop,但是对oop和c++还是很新的。我创建了头文件threevector.h,类threevector.cpp的文件和主程序文件main.cpp。我只想知道我做错了什么。
// threevector.h
#ifndef THREEVECTOR_H
#define THREEVECTOR_H
#include <iostream>
class threevector {
private:
double xcoord, ycoord, zcoord;
public:
threevector();
threevector(double x, double y, double z, char type);
void print ();
};
#endif // THREEVECTOR_H
//threevector.cpp
#include "threevector.h"
#include <cmath>
threevector() {
xcoord = 0.0;
ycoord = 0.0;
zcoord = 0.0;
}
threevector(double x, double y, double z, char type) {
if (type == 'c') {
// cartesian coordinate
xcoord = x;
ycoord = y;
zcoord = z;
}
else if (type == 'p') {
// polar coordinate
// x = r, y = phi, z = theta
xcoord = x*sin(y)*cos(z);
ycoord = x*sin(y)*sin(z);
zcoord = x*cos(y);
}
}
void print () {
std::cout << xcoord << '\t' << ycoord << '\t' << zcoord << std::endl;
}
// main.cpp
#include "threevector.h"
#include <cmath>
#include <iostream>
using namespace std;
int main() {
threevector v0;
v0.print();
threevector v1(-1,2,4.384,'c');
cout << "v1 = ";
v1.print();
return 0;
}
以下是我收到的错误消息:
main.cpp(.text+0x15): undefined reference to 'threevector::threevector()'
main.cpp(.text+0x15): undefined reference to 'threevector::print()'
main.cpp(.text+0x15): undefined reference to 'threevector::threevector::threevector(double, double, double, char)'
main.cpp(.text+0x15): undefined reference to 'threevector::print()'
[Error] ld returned 1 exit status
最佳答案
您定义了threevector
的方法错误。它应该是:
threevector::threevector() {
xcoord = 0.0;
ycoord = 0.0;
zcoord = 0.0;
}
threevector::threevector(double x, double y, double z, char type) {
if (type == 'c') {
// cartesian coordinate
xcoord = x;
ycoord = y;
zcoord = z;
}
else if (type == 'p') {
// polar coordinate
// x = r, y = phi, z = theta
xcoord = x*sin(y)*cos(z);
ycoord = x*sin(y)*sin(z);
zcoord = x*cos(y);
}
}
void threevector::print () {
std::cout << xcoord << '\t' << ycoord << '\t' << zcoord << std::endl;
}
所有
threevector
的方法都在threevector
的范围内。不要忘记像
main.cpp
一样编译它:g++ threevector.cpp main.cpp
由于
threevector
在同一目标文件中,因此将正确链接。关于c++ - C++中编译类时出现错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31479863/