如何修复此类模板错误?

时间:2015-09-05 02:44:32

标签: c++ class templates methods

这是我第一次尝试使用类模板(我是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;
}

number.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

number.cpp

#include "number.h"

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

1 个答案:

答案 0 :(得分:1)

尝试将#!/usr/bin/env perl use strict; use warnings; use File::Find::Rule; my @dirnames = qw( dirx temp_dir testdir nextdir ); my @dirs_to_search = map { "/tmp/$_" } @dirnames; my @files; for my $dir (@dirs_to_search) { push @files, find_files_in_dir($dir); } sub find_files_in_dir { my ($dir) = @_; my @subdirs = File::Find::Rule->directory->in( $dir ); my @txt_files; for my $subdir ( @subdirs ) { push @txt_files, sort glob "$subdir/*.txt"; } return @txt_files; } 包含在number.cpp中(作为临时解决方法),而不是包含main.cpp。或者将number.h的功能定义移至ToString(),并仅使用number.h

请参阅Why can templates only be implemented in the header file?