帮助我解决这个问题中的错误,其中我必须借助模板使用递归找到元素的总和

Hui Liu-MSFT 46,961 信誉分 Microsoft 供应商
2024-05-20T08:15:50.5233333+00:00
include <stdio.h>
include<iostream>
using namespace std;
class Array{
public :
int N;
Array()
{
cout << "Enter Size Of array: " << endl;
cin >> N;
}
};
template<class T>
class Recursion : public Array
{
int *A = new int [N];
public:
int findsum(int *A);
};
template<class T>
int Recursion<T>::findSum(int *A) //Returning sum of element using recursion
{
cout<<"\nenter Array\n";
for(int i=0;i<n;i++)
cin>>A[i];
if (N <= 0)
return 0;
return (findSum(A, N - 1) + A[N - 1]);
}
int main() //Driver code
{ Recursion<int> l;
cout<<l.findsum(A,N);
return 0;
}

Note:此问题总结整理于:Help me in solving the error in this question in which i have to find sum of element using recursion by the help of template also

C++
C++
一种通用的高级编程语言,作为 C 编程语言的扩展而创建,除了用于低级别内存操作的功能外,还具有面向对象、泛型和功能性等特点。
125 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Jiale Xue - MSFT 41,426 信誉分 Microsoft 供应商
    2024-05-20T09:01:18.73+00:00

    在你的代码中,我发现了一些问题,建议你复习一下构造函数和调用函数的相关知识,我修改了你的代码供大家参考和学习,请仔细比较。

    #include <stdio.h>  
    #include<iostream>  
    using namespace std;  
    class Array {  
    public:  
    	int N;  
    	Array()  
    	{  
    		cout << "Enter Size Of array: " << endl;  
    		cin >> N;		  
    	}  
    };  
    template<class T>  
    class Recursion : public Array  
    {	  
    public:  
    	int* A = new int[N];  
    	int findsum(int* A,int N);  
    	Recursion()  
    	{  
    		cout << "\nenter Array\n";  
    		for (int i = 0; i < N; i++)  
    			cin >> A[i];  
    	}  
    };  
    template<class T>  
    int Recursion<T>::findsum(int* A,int N) //Returning sum of element using recursion  
    {  
    	if (N <= 0)  
    		return 0;  
    	return (findsum(A, N - 1) + A[N - 1]);  
    }  
    int main() //Driver code  
    {  
    	Recursion<int> l;  
    	cout << l.findsum(l.A,l.N);  
    	return 0;  
    }  
    

    如果答案是正确的,请点击“接受答案”并点赞。 如果您对此答案还有其他疑问,请点击“评论”。

    注意:如果您想接收相关电子邮件,请按照我们的文档中的步骤启用电子邮件通知 此线程的通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助