0

I have removed all the unwanted segments. I am trying to pass pointers to an overloaded operator and use templates too. But this is still not working.

#include<iostream.h>
#include<conio.h>

class Test{
      private:
             int a;
      public:
             Test (){}
             Test(int k){
                a=k;
             }
             Test* operator +(Test *p){
                  Test *temp=new Test(this->a+p->geta());
                  return temp;
             }
             int geta(){
                  return a;
             }
};

template<class T>  
   T* sum(T* a,T* b){
   return a+b;
}

int main(){
    Test *t1,*t2;
    t1=new Test(5);
    t2=new Test(7);
    Test *z=sum(t1,t2);
    cout<<z->geta();
    getch();
}

3 Answers 3

3

Firstly, t1 is a pointer, and you are calling the add method incorrectly - should be t1->add(t2). Secondly, the sum() methods takes arguments which are not pointers, i.e. the template parameter is deduced as Test rather than Test*, hence you need to change the signature to something like:

template <typename T>
T* sum(T* a, T* b)
{
  return a->add(b); // or some variant...
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is there really any need to make it a template? As it is he is passing two ints to a perfectly good template and just adding them
@CashCow, in this instance, really no need - I was simply correcting his usage...
thanx....that t1.add was just a silly mistake...but i get wat u said abt the template...i was under the impression tht it wud include pointer references too...and i m just fooling around with templates...i dont intend to use this code segment newhr....i am a beginner u see....thanks agian....
1

Who teaches people to program C++ this way? iostream.h??? And an overload of operator+ that takes and returns a pointer?

sum will therefore fail if you are trying to use it for Test objects. As it is, it is adding ints, not Tests.

You have a pointer so when you call add you must use -> to invoke the function, but really this is a big mess.

2 Comments

wats wrong wid iostream.h....and i was jus playin arnd wid templates....my first program with templates....and nobody s teachin me...
@ankur: The normal way to use cout is to #include <iostream> ... std::cout << "etc.";
0

As Nim has already answered correctly. I will simply give some suggestions.

No need for this->a. Only a will suffice.

int d=a+p->geta();   
int k=sum(2,4); is again wrong as this is going to return class and not int.   

Moreover operator+ is not right. Please learn about the reference and try to learn from some good book. This is a nice try as a first program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.