簡體   English   中英

賦值運算符C ++

[英]Assignment operator C++

我正在嘗試實現賦值運算符,但我不斷收到一些錯誤:

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

在嘗試使用不同的解決方案時expected constructor, destructor, or type conversion before '&'我還在expected constructor, destructor, or type conversion before '&'遇到了expected constructor, destructor, or type conversion before '&'

日歷具有日期類型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) {};

這是在源文件中,因此其余代碼將找不到特化。 您應該將方法的實現移動到頭文件中,這樣,所有調用站點都可以替換自己的模板參數並專門化類和賦值運算符。

operator= body(實現)移動到.h文件。

由於模板是在需要時編譯的,因此會強制限制多文件項目:模板類或函數的實現(定義)必須與其聲明位於同一文件中。 這意味着我們無法在單獨的頭文件中分離接口,並且我們必須在使用模板的任何文件中包含接口和實現。

更多信息在這里

更新:如果有時某些聲明在源文件中聲明時有效,請確保該類的所有對象位於 同一源文件中 相同的轉換單元。

除了其他人所說的,類模板的成員函數模板定義的正確語法是:

template <typename T>
template <typename K>
Calendar<T>& Calendar<T>::operator=(const Calendar<K>& c_other)
{
    // your code here
}
template<class T>
class Calendar
{
public:
    T i;
    Calendar(const T & i_in):i(i_in){}
    template <class T2>
    Calendar <T>& operator=(const Calendar<T2> &);
};

template <class T>
 template <class T2>
Calendar<T>& Calendar<T>::operator=(const Calendar<T2>& t2)
{
 if (this == (void*) &t2) //avoid self assignment
  return *this; 

 this->i = t2.i; //implicit conversion here for example double to int or vice versa
 return *this;  
}

Condider這段代碼。 我稱之為非對稱賦值運算符,因為模板參數不同。 如果不存在隱式轉換,則必須自己進行轉換工作。 您可以使用以下代碼進行嘗試:

int main() {
    Calendar<double> tmp(2.0);
    std::cout << "Tmp i : " << tmp.i << std::endl;
    Calendar<int> tmp_2(1);
    std::cout << "tmp_2 i : " << tmp_2.i << std::endl;
    tmp = tmp_2;
    std::cout << "Tmp i : " << tmp.i << std::endl;
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM