0
点赞
收藏
分享

微信扫一扫

拷贝构造函数模板与拷贝赋值运算符模板

GhostInMatrix 2022-02-13 阅读 41
#include <iostream>
#include <string>
using namespace std;
template <typename T1>
class A
{
public:
    //构造函数模板
    template <typename T2>
    A(T2 v1, T2 v2);

    //成员函数模板
    template <typename T3>
    void myft(T3 tmpt) 
    {
        cout << tmpt << endl;
    }
    T1 m_ic;
    static constexpr int m_stcvalue = 200;
public:
    A(double v1, double v2)
    {
        cout << "A(double v1, double v2)" << endl;
    }
    A(T1 v1, T1 v2)
    {
        cout << "A(T1 v1, T1 v2)" << endl;
    }
public:
    //拷贝构造函数模板
    template <typename U>
    A(const A<U>& other)
    //A(A<U>& other)
    {
        cout << "A::A(const A<U>& other)" << endl;
    }
    //拷贝赋值运算符模板
    template <typename U>
    A<T1>& operator=(const A<U>& other)
        //A<T1>& operator=(A<U>& other)
    {
        cout << "operator=(const A<U>& other)" << endl;
        return *this;
    }
};
//类外定义
template <typename T1>
template <typename T2>
A<T1>::A(T2 v1, T2 v2)
{
    cout << "A::A(T2,T2)执行了!" << endl;
}
int main()
{
    A<float> a(11.1f, 12.2f);
    a.m_ic = 16.2f;
    A<float> a1(a);
    return 0;
}

//拷贝构造函数模板与拷贝赋值运算符模板的参数如果不是const,则不会调用。

如果带上const,并且又要进行相应的调用,那么这里的a1的类型需要与a的类型不一致,比如是int.

举报

相关推荐

0 条评论