c++ - 如何使用 C++ 模板实现 int、string、float 和 date 对象的数组?
问题描述
编写一个程序,使用类模板创建和显示整数、浮点数、字符串和日期对象的数组(其中日期对象使用整数月、日、年属性对日期建模)。
我能够显示整数、浮点数和字符串的数组,但在 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
函数中,该函数调用<<
的myarray
类型为T
:
cout << setw(7) << j << setw(13) << myarray[j] <<endl;
在这里,它期望myarray[j]
可以调用,和,但是你的operator<<
类没有提供使用,它怎么知道它应该如何输出?它不会知道打电话。相反,您应该只提供一个in :int
float
std::string
Date
operator<<
print_date
operator<<
Date
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
同样,您的班级也可以使用它。
推荐阅读
- reactjs - How to take a photo using callee's phone camera in React Native like Facetime?
- javascript - Promise.all not awaiting for the promises?
- python-3.x - 设置 Azure EnvironmentCredential()
- .net - .NET Core 3.1 Razor Model in _Layout page
- awk - awk 输出,第一列有空格
- python - Having trouble cleanly porting this C++ `for` loop to Python
- r - 在ggplot中添加图例-点/线和段
- python - Read csv files in multiple zip files by using one csv as an example and loop
- r - Use prop_test over multiple summary stats
- scala - pass batch size in deleteByQuery [elasticsearch] [scala]