问题
I have to do a custom "vector" class in c++ as homework for my university but I'm struggling with the templates.
I get this error after I change all the variables' types to the type template 'typename T'. The thing is that the compiler only points at the functions that are declared as "friend" functions. Namely (operators '==' and '<<') as seen from compiler's message:
Undefined symbols for architecture x86_64: "operator==(Vector const&, Vector const&)", referenced from: _main in main.o "operator<<(std::__1::basic_ostream >&, Vector)", 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)
Here's the declaration of these two friend operator functions in the header file and their implementation.
friend ostream& operator <<(ostream& out, Vector<T> x);
friend bool operator == (const Vector<T> &lop, const Vector<T> &rop);
template <typename T>
 bool operator == (const Vector<T> &lop, const Vector<T> &rop){
    if(lop.size() != rop.size()){
 return false;
}
else{
    int counter = 0;
    for(int i = 0; i < lop.size(); i++){
        for(int j = 0; j < rop.size(); j++){
            if(lop.values[i] == rop.values[j]){
                counter++;
            }
        }
if((counter == lop.size()) && (counter == rop.size())){
            return true;
        }
    }
}
return false;
}
template <typename T>
ostream& operator <<(ostream& out, Vector<T> x)
{
out << "[";
for(int i = 0; i < x.size(); i++){
    out << x.values[i];
    if(i + 1 != x.size()){
        out << ", ";
    }
}
out << "]";
return out;
}
In the main() function I just tested these two operators:
#include <iostream>
#include "vector.hpp"
#include "vector.cpp"
using namespace std;
int main (){
    Vector<double> second(10);
    Vector<double> third {1.0, 2.0, 3.0, 4.0, 5.0};
    cout << third << endl;
    Vector<double> v(10);
    Vector<double> k(10);
    if(k == v){
    cout << "YES" << endl;
}
    else{
    cout << "NO" << endl;
}
    return 0;
}
I don't understand why I get this error so I would really appreciate your help!
回答1:
You should add template <typename T> in your friend declaration in class Vector.
template <typename T>
friend ostream& operator <<(ostream& out, Vector<T> x);
template <typename T>
friend bool operator == (const Vector<T> &lop, const Vector<T> &rop);
    来源:https://stackoverflow.com/questions/42979112/ld-symbols-not-found-for-architecture-x86-64-clang-error-linker-command-fai