簡體   English   中英

如何在臨時容器類中實現復制構造函數和賦值運算符?

[英]How to implement copy constructor and assignment operator in a templatic container class?

我不知道如何在副本構造函數或賦值構造函數中將int轉換為double。 可能嗎? 怎么做?

template <typename T>
class Container {
public:
    Container() { //... }
    Container(const Container& y) { //... }
    Container& operator=(const Container& y) { //... }
    ~Container() { //... }
private:
    // ...
};

int main() {
    Container<int> ci;
    Container<double> cd;
    ci = cd;
}
 no match for 'operator=' (operand types are 'Container<double>' and 'Container<int>') candidate: Container<T>& Container<T>::operator=(const Container<T>&) [with T = double] 

對於您的Container模板,類定義內所有普通Container實例都等於Container<T> 因此,對於int的模板參數,則所有Container都等於Container<int> 這意味着您的operator=重載僅接受Container<int>參數。 您擁有的賦值運算符聲明等於

Container<T>& operator=(const Container<T>& y);

對於int模板參數將是

Container<int>& operator=(const Container<int>& y);

如果您希望能夠接受其他類型作為參數,則需要自己制作重載的運算符模板:

template<typename U>
Container& operator=(const Container<U>& y);
//                                  ^^^
//  Note use of new template argument here

暫無
暫無

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

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