【问题标题】:Class template linker error类模板链接器错误
【发布时间】:2012-08-19 17:22:39
【问题描述】:

我一直在尝试创建一个笛卡尔类,其中对象是笛卡尔点上的 2 个点(int 或 double)。然后我想重载

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

我不明白我的错误在哪里。

标题

#include <iostream>    

using namespace std;

template <class first, class second>
class cartesian
{

public:
    cartesian(first, second);

    //double getslope(cartesian &obj1, cartesian &obj2);

    friend ostream& operator<< (ostream &out, cartesian &cPoint);                

private:
    first x;
    second y;

};

CPP 文件

#include "cartesian.h"
#include <iostream>

using namespace std;


template<class first,class second>

cartesian<first, second>::cartesian(first a, second b)
:x(a), y(b)
{}

/*
// between obj1 and obj2
template<class first,class second>
double cartesian<first, second>::getslope(cartesian &obj1, cartesian &obj2){

    return ((obj2.y-obj1.y)/(obj2.x-obj1.y));
}

*/


template<class first,class second>

ostream&  operator<< (ostream &out,const cartesian<first, second> &cPoint)
{
    // Since operator<< is a friend of the Point class, we can access
    // Point's members directly.
    out << "(" << cPoint.x << ", " <<
    cPoint.y << ")";

    return out;
}

主要

#include <iostream>
#include "cartesian.h"

using namespace std;

int main()
{

    cartesian<double, int> ob11(3.4, 6);
    return 0;
}

【问题讨论】:

  • 问题是在 C++ 中处理大型模板项目非常糟糕。在 main 中尝试 #include cartesian.cpp。

标签: c++


【解决方案1】:

您需要将实现放在头文件或头文件包含的文件中。编译器需要访问代码才能“构建”您在 main 中需要的 cartesian&lt;double, int&gt; 特化。

例如,这里我们将构造函数的实现放在类声明中:

template <class first, class second>
class cartesian
{

public:
    cartesian(first, second) :x(a), y(b) {}
};

它不必进入类声明本身,但代码必须可以从头文件中访问。

【讨论】:

  • 将实现放在头文件中是什么意思?什么实施?对不起我的菜鸟。
  • @EEstud 我的意思是函数的定义,即您当前在 .cpp 文件中的内容。
  • 那么,我还需要在头文件中构造函数吗?一般我们是在cpp里面做的,但是因为是模板,所以需要在头文件中构造?我明白了吗?
  • @EEstud 正确,并删除.cpp,一些构建系统可能会尝试自动编译它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 2015-09-02
  • 1970-01-01
相关资源
最近更新 更多