2014-03-26 102 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