[英]How should I implement a copy constructor & assignment operator for a matrix class?
[英]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.