I am from Java backgroung and new to C++.
There is a template which i have made.
template <class T>
class Shape {
int val,val_new;
public:
Shape(T initval)
{
val=initval;
}
T get()
{
return val;
}
void set (T newval)
{
val_new = newval;
}
void copy()
{
this.val= val_new;
}
};
There is a class Rectangle to use this template
#include <iostream>
#include<math.h>
using namespace std;
class Rectangle
{
private:
Shape<TwoPoint> val;
TwoPoint newval;
public:
Rectangle(TwoPoint i)
{
val = new Shape<TwoPoint> (i);
}
Shape<TwoPoint> read()
{
return val;
}
void load(TwoPoint newval)
{
load_called=1;
this.newval=newval;
}
void increment()
{
val=val+1;
}
void decrement()
{
val= val-1;
}
void actions()
{
if (load_called)
value.set(new TwoPoint(newval));
}
};
TwoPoint is a class used for generics.
class TwoPoint
{
int width;
int value;
public:
TwoPoint(int v, int w)
{
value=v;
width=w;
}
TwoPoint(TwoPoint t)
{
value= t.value;
width= t.width;
}
int getWidth()
{
return width;
}
int getValue()
{
return value;
}};
But i am getting a lot of errors like constructor mismatches, conversion failures. Can somebody please help me.
There are errors like
In constructor `Rectangle::Rectangle<TwoPoint>':
error: no matching function for call to Shape<TwoPoint>:: Shape()'
note: candidates are: Shape<T>::Shape<T> with [T = TwoPoint]
Two similar errors are there
First; in the following piece of code,
thisis indexed with ‘.’, butthisis a pointer so you should useval = val_new;(implicitlythis->val = val_new;):… should be…
Same problem at
Rectangle::load.Secondly: like others are saying, you should use
T val, val_newinstead ofint val, val_new.And last but not least:
valshould be initalized like this:There are two reasons for this:
valis not initalized like this, the default constructor (Shape<T>::Shape()) is used, which does not exist.newkeyword allocates new memory in C++ and returns a pointer. It should be left away sincevalis not a pointer but a value.At constructors you can intialize member values by calling their constructors, or calling them with their value (auto-generated copy constructor). This should be prefixed with a colon an followed by the function body.