我正在尝试实现赋值运算符,但我不断收到一些错误:
calendar.cpp:25: error: prototype for ‘lab2::Calendar<T>& lab2::Calendar<T>::operator=(lab2::Calendar<K>)’ does not match any in class ‘lab2::Calendar<T>’
calendar.h:19: error: candidate is: template<class T> template<class K> lab2::Calendar& lab2::Calendar::operator=(lab2::Calendar<K>)
make: *** [calendar.o] Error 1
在尝试不同的解决方案时,我还遇到过预期的构造函数、析构函数或“&”之前的类型转换
。
日历的日期类型为 T,即日历中的日期可以不是公历。但我也希望能够从具有其他日期类型的日历分配给日历。
这是我的声明和实现。
//calendar.h
template <typename T>
class calendar {
//...
template <typename K> Calendar& operator=(const Calendar<K> c_other);
//...
}
//calendar.cpp
//...
template <typename T, typename K>
Calendar<T>& Calendar<T>::operator=(const Calendar<K> c_other) {};
//...
将不胜感激任何帮助。
最佳答案
恐怕您对模板的使用有问题。 首先你想使用引用传递,而不是值。这样,您就可以控制创建参数对象。
template <typename K> Calendar& operator=(const Calendar<K>& c_other);
那么,真正的问题来了:
template <typename T, typename K>
Calendar<T>& Calendar<T>::operator=(const Calendar<K>& c_other) {};
这在源文件中,因此其余代码将找不到特化。您应该将方法的实现移到头文件中,这样,所有调用站点都可以替换自己的模板参数并专门化类和赋值运算符。
关于c++ - 赋值运算符 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7866751/