如何在临时容器类中实现复制构造函数和赋值运算符?

and*_*ini 2 c++

我不知道如何在副本构造函数或赋值构造函数中将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;
}
Run Code Online (Sandbox Code Playgroud)
no match for 'operator=' (operand types are 'Container<double>' and 'Container<int>')

candidate: Container<T>& Container<T>::operator=(const Container<T>&) [with T = double]
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 6

For your Container template all instances of plain Container inside the class definition is equal to Container<T>. So for a template argument of int then all Container is equal to Container<int>. And that means your operator= overload only takes a Container<int> argument. The assignment operator declaration you have is equal to

Container<T>& operator=(const Container<T>& y);
Run Code Online (Sandbox Code Playgroud)

Which for an int template argument would be

Container<int>& operator=(const Container<int>& y);
Run Code Online (Sandbox Code Playgroud)

If you want to be able to accept other types as arguments, you need to make the overloaded operators templates themselves:

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