如何使用 c++ 模板实现整数、字符串、浮点数和日期对象的数组



>编写一个程序,该程序使用类模板创建和显示整数、浮点数、字符串和 Date 对象数组(其中 Date 对象使用整数月、日、年属性对日期进行建模(。

我能够显示整数、浮点数和字符串的数组,但日期对象的数组有问题。我不确定如何从模板类调用打印日期函数(在日期类中(。

template< typename T > 
class Myarray {
private:
    int size;
    T *myarray;
public:
    // constructor with user pre-defined size
    Myarray(int s , T* array) {
        size = s;
        myarray = new T[size];
        for (size_t i = 0; i < size; ++i)
        {
            myarray[i] = array[i]; // Copy into object
        }
    }
    // calss array member function to set element of myarray 
    // with type T values
    void setArray(int elem, T val) {
        myarray[elem] = val;
    }
    // for loop to display all elements of an array
    void getArray() {
        for (int j = 0; j < size; j++) {
            // typeid will retriev a type for each value
            cout << setw(7) << j << setw(13) << myarray[j] <<endl;
        }
        cout << "-----------------------------" << endl;
    }
};
class Date {
private:
    int day;
    int month;
    int year;
public:
    Date() {
        day = month = year = 0;
    }
    Date(int day, int month, int year) {
        this->day = day;
        this->month = month;
        this->year = year;
    }
    void print_date(void) {
        cout << day << "/" << month << "/" << year << endl;
    }

};
int main()
{
    // instantiate int_array object of class array<int> with size 2
    int array1[] = { 1,2,3,4,5 };
    Myarray< int > int_array(5,array1);
    int_array.getArray();

    float array2[] = { 1.012, 2.324, 3.141, 4.221, 5.327 };
    Myarray<float> b(5, array2);
    b.getArray();

    std::string array3[] = { "Ch1","Ch2","Ch3","Ch4","Ch5" };
    Myarray<std::string> c(5, array3);
    c.getArray();

    Date array4[] = { Date(10, 18, 2019), Date(1, 01, 2019), Date(7, 04, 2019),
                    Date(12, 31, 2019), Date(12, 25, 2019) };
    Myarray<Date> d(5, array4);
    d.getArray();

    return 0;
}

收到错误消息:

Error   C2679   binary '<<': no operator found which takes a right-hand operand of type 'Date'

问题出在您的getArray函数中,该函数在类型为Tmyarray上调用<<

cout << setw(7) << j << setw(13) << myarray[j] <<endl;

在这里,它期望myarray[j]可以用operator<<调用,这对于intfloatstd::string是正确的,但是你的Date类没有提供要使用的operator<<,它怎么知道它应该如何输出?它不会知道打电话给print_date.相反,您应该只在Date中提供一个operator<<

friend std::ostream& operator<<(std::ostream& oss, const Date& d)
{
    oss << d.day << "/" << d.month << "/" << d.year << "n";
    return oss;
}

现在你可以这样写:

Date d;
std::cout << d;

同样,您的MyArray类也可以使用它。

最新更新