2014-03-26 101 views
0

我编译的代码,但此错误消息,我不知道这意味着什么终端出现了。 有人可以解释或给我一些提示吗?我不知道这个错误是什么意思

/tmp/ccZ95DTV.o: In function `main': homework3_test.cpp:(.text+0x514): 
undefined reference to `std::vector<int, std::allocator<int> >& 
apply<PowerN>(std::vector<int, std::allocator<int> >&, PowerN)' 
collect2: ld returned 1 exit status 

代码:

int test_power1, test_power2, test_power3; 
PowerN power_three(3); 
//test_power will now be 1 
power_three(test_power1); 
//test_power will now be 3 
power_three(test_power2); 
//test_power will now be 9 
power_three(test_power3); 
if (1 == test_power1) { 
    std::cout<<"PowerN works for 3**0! +10\n"; 
    score += 10; 
} 
else { 
    std::cout<<"PowerN failed on 3**0!\n"; 
} 

if (3 == test_power2 and 9 == test_power3) { 
    std::cout<<"PowerN works for 3**1 and 3**2! +10\n"; 
    score += 10; 
} 
else { 
    std::cout<<"PowerN failed for 3**1 and 3**2!\n"; 
} 

std::vector<int> test_power_v(3); 
PowerN power_lessfour(-4); 
//apply turns the vector into [1, -4, 16] 
apply(test_power_v, power_lessfour); 
std::vector<int> check_power_v; 
check_power_v << 1 << -4 << 16; 
if (test_power_v == check_power_v) { 
    std::cout<<"Applying PowerN with -4 works! +10\n"; 
    score += 10; 
} 
else { 
    std::cout<<"Applying PowerN with -4 failed!\n"; 
} 

那么,什么是加是我的老师给出的测试代码。如果你想看看我的代码实现,请告诉我。

所以这行代码是我的头文件

template <typename T> 
vector<int>& apply(vector<int>& v, T function); 

,这些都是在cpp文件

template <typename T> 
vector<int>& apply(vector<int>& v, T function) { 
    for (vector<int>::iterator I = v.begin(); I != v.end(); ++I) { 
     function(*I); 
    } 
    return v; 
} 

谢谢你们的落实。我解决了这个问题。模板必须在头文件中定义,而不是在实现文件中定义。

+0

如果ü可以共享代码 – balaji

+0

你能告诉一些代码吗? – Claudiordgz

+0

您可能在尝试调用其中一个变量/对象时拼错了它。邮政编码! – Coderchu

回答

2

这意味着你创建了一个原型与签名功能:

template <typename PowerN> vector<int> apply(vector<int>&, PowerN) 

你叫它,但你从来没有真正在任何来源的写了身体这个功能,你问过你的编译器建立。

你有没有:

  • 错字这个函数的编写身体的时候叫什么名字?
  • 提供的功能编写它的身体时(例如离开过一个&或东西)略有不同的签名?
  • 在不是正在构建的源文件中写入正文?

发布您的代码将帮助人们更好地诊断。

+1

考虑到它是一个模板,它也不能在不同的TU中。 – chris