未定义的构造函数和函数上的未定义符号,为什么?

时间:2018-07-29 10:18:15

标签: c++ class

我有一个物理Vector类,它需要一个构造函数和字符串函数。当我编译类时,出现以下错误:

我这样调用编译器:g++ main.cpp -o main

Undefined symbols for architecture x86_64:
  "Vector::toString()", referenced from:
      _main in main-3acaf8.o
  "Vector::Vector()", referenced from:
      _main in main-3acaf8.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

这暗示我还没有定义构造函数和toString函数。这是我的代码,该如何解决?

头文件:

#include <iostream>
#include <cmath>

class Vector {

    const static int d = 3, xPos = 0, yPos = 1, zPos = 2;
    double components[d];

    public:
        Vector();
        Vector(double x, double y, double z);
        Vector(const Vector &v1);
        void setVector(double x, double y, double z);
        double getX();
        double getY();
        double getZ();
        double magnitude();
        Vector getUnitVector();
        double dot(Vector v1, Vector v2);
        void scale(double c);
        Vector add(Vector v1, Vector v2);
        Vector subtract(Vector v1, Vector v2);
        Vector crossProduct(Vector v1, Vector v2);
        void toString();
};

cpp文件:

#include "vector.hpp"

Vector::Vector(){
    for(int i = 0; i < d; i++)
        components[i] = 0;

... // all other functions

void Vector::toString(){
    printf("x: %lf, y: %lf, z: %lf\n", 
        components[0], components[1], components[2]);
}

谢谢。

0 个答案:

没有答案