Jump to content

using template with operator overloading (inheritence)

- - - - -

  • Please log in to reply
4 replies to this topic

#1
dupdupdup

dupdupdup

    Newbie

  • Members
  • Pip
  • 2 posts
I've been scratching my head ever since. Please advice if anyone can!
My operator overloading works, but if i use it with templates than it dosent see Class B values. to note: my template works with class A but not B! :(

Class A
{
bool operator<(A pd)
{
return compareLessThan(pd);
}//end of operator< method

bool compareLessThan(A pd)
{
return x>pd.x
}

Class B:public Class A
{
bool compareLessThan(B pd)
{
return (x+y)>(pd.x+pd.y)
}
}

this works if i do not use templates.
but once i implements templates.
the values templates sees are only zero!

template<class T>
bool lessThan(T para1,T para2)
{
return para1<para2;
}//end of lessThan method

#2
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
Your code works, aside from some syntax errors you forgot. Can you show us how you call them?
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#3
dupdupdup

dupdupdup

    Newbie

  • Members
  • Pip
  • 2 posts
first of all thanks for your reply! yeah the code there wasnt the real code, i jsut simplify it by typing out a sample.
anyway this is how i call it.
when i do pd1<pd2, it works.
but when i do a call from the template function. it dosent work.
i did a check, when this getScalarValue()) calls from template.h header file, it returns 0 for class b.
if i did the same below but for class a( base class) it works perfect.

int main()
{
//class b
B pd1(45,43,41);
B pd2(43,43,123);

if(pd1<pd2==true)
{
cout<<"test"<<endl;
}

if(lessThan(pd1,pd2)==true)
{
cout<<pd1.getValue()<<endl;
cout<<"Less than"<<endl;
cout<<pd2.getValue()<<endl;
}
else
{
cout<<"error"<<endl;
}
}

Edited by dupdupdup, 14 November 2011 - 03:57 PM.


#4
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
You can't make a template function and pass classes. Templates work on primitive data types (int, char, bool, ...).

Since you already have operator < overloaded, why not try something like this:
bool lessThan(const B& lhs, const B& rhs) {
    return lhs < rhs;
}

A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#5
AKMafia001

AKMafia001

    Programmer

  • Members
  • PipPipPipPip
  • 119 posts
Why not you code a templated class?

Like,


template <class T>

class MyClass

{

private:

	T num;

public:

 	MyClass(T n)

	{ num = n; }	 


    	friend bool operator>(MyClass &c1, MyClass &c2)

	{

	        return (c1.num > c2.num) ? true: false;

	}

};



Hope this helps!
I think i'm able to write a code for printing "Hello, World!". Proud of that!




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users