【问题标题】:How to fix this class template error? [duplicate]如何修复此类模板错误? [复制]
【发布时间】:2015-12-01 06:12:24
【问题描述】:

这是我第一次尝试使用类模板(我是 C++ 新手)

我正在尝试创建一个非常简单的Number 类。首先,我正在创建一个ToString 方法。截至目前,出于测试目的,我只想让ToString 返回字符串"testing"

当我运行我的代码时,我收到以下错误:

Undefined symbols for architecture x86_64: "Number<int>::ToString()", 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) make: *** [build/ml] Error 1

这是我的代码,感谢任何帮助:

main.cpp

#include "number.h"

int main(int argc, char* argv[]) {
    Number<int> x(15);
    x.ToString();
    return 0;
}

数字.h

#ifndef _NUMBER_
#define _NUMBER_

#include <iostream>

template <class T> 
class Number {
    private:
        T m_val;
    public:
        Number(T val) : m_val(val) {};
        std::string ToString();
};

#endif

数字.cpp

#include "number.h"

template<class T> 
std::string Number<T>::ToString() {
    return std::string("testing");  
}

【问题讨论】:

  • 与普通代码不同,您必须将模板完全放在头文件中。 (这是一种简化,但最简单的解决方案)
  • 使ToString 成为一个常量函数。你不需要用std::string包围引用

标签: c++ class templates methods


【解决方案1】:

尝试在main.cpp 中包含number.cpp(作为临时解决方法),而不是包含number.h。或者将ToString()的函数定义移到number.h中,只使用number.h

Why can templates only be implemented in the header file?

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-06-08
  • 2021-12-27
  • 2018-07-27
  • 2020-05-15
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
相关资源
最近更新 更多