我有一个模板类(Word):
template<int C>
class Word {
...
}
我想添加一个运算符(operator):
friend Word<C> operator&(Word<C>& word1, Word<C>& word2); // & operator between all bits
所以现在我有:
template<int C>
class Word {
...
friend Word<C> operator&(Word<C>& word1, Word<C>& word2); // & operator between all bits
}
template<int C>
Word<C> operator&(Word<C>& word1, Word<C>& word2) {
Word<C> ans = new Word<C>;
for (int i = 0; i < C; i++) {
ans[i] = word1[i] & word2[i];
}
return ans;
}
但我得到了这个标记:
Multiple markers at this line
- (if this is not what you intended, make sure the function template has already been declared and add <> after the function name
here)
- friend declaration 'Word<C> operator&(Word<C>&, Word<C>&)' declares a non-template function [-Wnon-template-friend]
使用运算符时出现此错误:
undefined reference to `operator&(Word<8>&, Word<8>&)'
使用代码:
Word<C> tmp1 = (words[i] & mask);
最佳答案
先声明函数 function,然后再将其设为友元。
// Forward declare the class.
template<int C> class Word;
// Declare the function.
template<int C> Word<C> operator&(Word<C>& word1, Word<C>& word2);
那么,类中的friend
声明就OK了。
关于c++ - 如何在 C++ 中使用类模板声明新运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33654246/