【问题标题】:template member functions in c++c++中的模板成员函数
【发布时间】:2011-09-12 16:18:00
【问题描述】:

我在 c++ 中遇到泛型问题。我有两个 Matrix.h 和 Matrix.cpp 文件。这是文件:

#pragma once
template<class T>
class Matrix
{
    public:
        static T** addSub(int size,T** firstMatrix,T** secondMatrix,int operation);
}

和 Matrix.cpp

#include "Martix.h"
template<class T>
static T** Matrix<T>::addSub( int n,T **firstMatrix,T **secondMatrix,int operation)
{
    //variable for saving result operation
    T **result = new T*[n];

    //create result matrix
    for( int i=0;i<n;i++)
        result[i] = new T[n];

    //calculate result
    for( int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            result[i][j] = 
            (operation == 1) ? firstMatrix[i][j] + secondMatrix[i][j]:
                                firstMatrix[i][j] - secondMatrix[i][j];

    return result;
}

当我运行这些时,我得到以下错误:

Error   1   error LNK2019: unresolved external symbol "public: static int * * __cdecl Matrix<int>::addSub(int,int * *,int * *,int)" (?addSub@?$Matrix@H@@SAPAPAHHPAPAH0H@Z) referenced in function "public: static int * * __cdecl Matrix<int>::strassenMultiply(int,int * *,int * *)" (?strassenMultiply@?$Matrix@H@@SAPAPAHHPAPAH0@Z) C:\Users\ba.mehrabi\Desktop\Matrix\matrixMultiplication\main.obj    matrixMultiplication

有什么问题?

【问题讨论】:

  • 在声明的同一编译单元中是否有模板方法定义?
  • 您拼错了包含文件的名称。我想知道您是否在这里给我们您的真实代码,或者您是否只是从记忆中写下一些小说……此外,C++ 没有“泛型”;如果您具有 Java 背景,那么可能值得您花时间熟悉常见的 C++ 习惯用法,它们完全不同。例如,在 C++ 中你应该很少或永远不会说 new

标签: c++ templates


【解决方案1】:

很遗憾,您不能在 *.cpp 文件中声明模板类。完整的定义必须保留在头文件中。这是许多 C++ 编译器的规则。

看到这个:http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

  1. 模板不是类或函数。模板是一种“模式” 编译器用来生成一系列类或函数。
  2. 为了让编译器生成代码,它必须同时看到 模板定义(不仅仅是声明)和具体的 类型/用于“填写”模板的任何内容。例如,如果您是 尝试使用 Foo,编译器必须同时看到 Foo 模板 以及您正在尝试制作特定 Foo 的事实。
  3. 您的编译器可能不记得一个 .cpp 的详细信息 编译另一个 .cpp 文件时的文件。可以,但大多数都可以 不是,如果您正在阅读此常见问题解答,它几乎肯定不会。 顺便说一句,这被称为“分离编译模型”。

该链接有一个解决方法,但请记住,模板是一个美化的宏,因此头文件可能是它的最佳位置。

this SO 帖子的海报展示了解决方法。

【讨论】:

    【解决方案2】:

    首先,类模板的函数定义,应该放在header本身。

    其次,如果您在类外定义static 成员函数(尽管在标头本身中),则不要使用static 关键字(在定义中)。仅在声明中需要。

    【讨论】:

      【解决方案3】:

      添加

      template Matrix<int>;
      

      在您的 cpp 文件的末尾,它将起作用。但是你需要学习一些关于模板的东西,否则你将不得不处理很多你不了解的问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        • 2018-01-28
        • 1970-01-01
        • 1970-01-01
        • 2013-09-24
        相关资源
        最近更新 更多