C++面向对象程序设计 034:goodcopy ---- (北大Mooc)


专题博客链接

北大C++ POJ课后习题博客全解记录


原题题目

在这里插入图片描述

#include <iostream>
using namespace std;


template <class T>
struct GoodCopy {
    
    
// 在此处补充你的代码
};

int a[200];
int b[200];
string c[200];
string d[200];

template <class T>
void Print(T s,T e) {
    
    
	for(; s != e; ++s)
		cout << * s << ",";
	cout << endl;
}

int main()
{
    
    
	int t;
	cin >> t;
	while( t -- ) {
    
    
		int m ;
		cin >> m;
		for(int i = 0;i < m; ++i)
			cin >> a[i];
		GoodCopy<int>()(a,a+m,b);
		Print(b,b+m);
		GoodCopy<int>()(a,a+m,a+m/2);
		Print(a+m/2,a+m/2 + m);

		for(int i = 0;i < m; ++i)
			cin >> c[i];
		GoodCopy<string>()(c,c+m,d);
		Print(c,c+m);
		GoodCopy<string>()(c,c+m,c+m/2);
		Print(c+m/2,c+m/2 + m);
	}
	return 0;
}

前引分析

因为也是C++初学者 难免出现各种问题 对有些地方理解不了
比如就这两道题 我因为理解不了两个地方而导致卡了一晚上和今天一上午

这里的分析我只针对 我之气那理解不了为什么这里是这样写的
如果有错欢迎指出 确实这里多个括号让我觉得很突兀

GoodCopy<int>()(a,a+m,b);

我现在的理解是 这里的一个括号GoodCopy () 因为是调用缺省函数
生成一个一个临时对象 因为我们的括号需要先生成一个临时对象我们才能使用()

而我们如果不加括号的话 我们连对象都没有了 括号重载也无从使用


代码实现

    public:
    void operator()(const T* startptr,T* endptr,T* setptr)
    {
    
    
        T* temp = endptr-1;
        setptr += (endptr - startptr-1);
        for(;temp >= startptr;temp--,setptr--)
            *setptr = *temp;
    }

猜你喜欢

转载自blog.csdn.net/qq_37500516/article/details/115015945