数组类模板

//
//  main.cpp
//  project
//
//  Created by 徐伟 on 6/8/16.
//  Copyright © 2016 fizz_i. All rights reserved.
//


#include <iostream>

using namespace std;
template <class T>
class Array {
private:
    T*list;
    int size;
public:
    Array(int size=50);
    Array(const Array<T> &a);
    ~Array();
    Array<T> &operator =(const Array<T> &rhs);
    T &operator [](int i);
    operator T*();
    
    
};
template<class T>
Array<T>::Array(int sz)
{
    size=sz;
    list=new T[size];
}
template<class T>
Array<T>::Array(const Array<T> &a)
{
    size=a.size;
    list=new T[size];
}
template<class T>
Array<T>::~Array()
{
    delete []list;
}
template<class T>
Array<T> &Array<T>::operator =(const Array<T> &rhs)
{
    if (&rhs != this)
    {
        //如果本对象中数组大小与rhs不同,则删除数组原有内存,然后重新分配
        if (size != rhs.size)
        {
            delete [] list; //删除数组原有内存
            size = rhs.size;    //设置本对象的数组大小
            list = new T[size]; //重新分配n个元素的内存
        }
        //从对象X复制数组元素到本对象
        for (int i = 0; i < size; i++)
            list[i] = rhs.list[i];
    }
    return *this;   //返回当前对象的引用
}
template<class T>
T &Array<T>::operator[](int i)
{
    return *(list+i);
}
template<class T>
Array<T>::operator T*()
{
     return list;
}
int main()
{
    Array<int> a(10);
    Array<int> b(a);
    Array<int> c;
    
    for (int i=0; i<10; ++i) {
        cin>>a[i];
    }
    b=a;
    c=b;
    for (int i=0; i<10; ++i) {
        cout<<c[i];
    }
    return 0;
}

转换操作符(conversion operator)是一种特殊的类成员函数。它定义将类类型值转变为其他类型值的转换。转换操作符在类定义体内声明,在保留字operator之后跟着转换的目标类型:

class SmallInt

{

public:

SmallInt(int i=0); val(i)

{

if(i < 0 || i > 255)

{

throw std::out_of_range("Bad SmallInt intializer");

}

}

operator int() const

{

return val;

}

private: 

std::size_t val;

};

转换函数采用如下通用形式:

operator type();

这里,type表示内置类型名、类类型名或有类型别名所定义的名字。对任何可作为函数的返回类型(除了void之外)。一般而言,不允许转换为数组或函数类型,转换为指针类型(数据和函数指针)以及引用类型是可以的。

注解: 转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空。

下述所有的声明都是错误的:

operator int(Small Int& ); // error:nonmember

class SmallInt

{

public:

int operator int(); // error: return list

operator int(int = 0);  // error:parameter list

// ...

};

虽然转换函数不能指定返回类型,但是每个转换函数必须显示返回一个指定的值。例如,operator int返回一个int值;如果定义operator Sales_item,它将返回一个Sales_item对象,诸如此类。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值