I was on codepad and I was trying to build up my skills using C++. I'd never used templates much before, so I tried looking into how to use them. The code below is the result, and unfortunately, it does not work. I did try to search for solutions to my problem, but since I don't have much experience using templates, I couldn't make any connections between my problem and other problems. So, I decided to ask for help.
template <class A>
class Vector2 {
public:
A x,y;
Vector2(A xp, A yp){
this->x = xp;
this->y = yp;
}
};
template <class B, class A>
class rayToCast {
public:
rayToCast(B angle, Vector2<A> origin, Vector2<A> point1, Vector2<A> point2){
this->RAngle = angle;
this->Point1 = point1;
this->Point2 = point2;
}
private:
B RAngle;
Vector2<A> point1,point2;
};
int main(){
rayToCast<short int, float> ray(45, Vector2<float>(0.0, 0.0), Vector2<float>(-10.0, -3.0), Vector2<float>(5.0, 7.0));
return 0;
}
Here's the output:
t.cpp: In constructor 'rayToCast<B, A>::rayToCast(B, Vector2<A>, Vector2<A>, Vector2<A>) [with B = short int, A = float]':
t.cpp:26: instantiated from here
Line 14: error: no matching function for call to 'Vector2<float>::Vector2()'
compilation terminated due to -Wfatal-errors.
Any help is appreciated.
The rayToCast
constructor tries to initialize point1
and point2
by calling Vector2
's default constructor. But it doesn't have one.
You either have to provide a default constructor for the vector class, or explicitly initialize the members of rayToCast
. One way is to do like this:
rayToCast(B angle, Vector2<A> origin, Vector2<A> point1, Vector2<A> point2)
: RAngle(angle), point1(point1), point2(point2)
{ }
You have two issues in your code:
Vector2 has no default constructor, default constructor will be called when pass Vector2 to rayToCast
constructor.
rayToCast(B angle, Vector2<A> origin, Vector2<A> point1, Vector2<A> point2)
You need to add default constructor to Vector2 and initialize x,y
to default value:
template <class A>
class Vector2 {
public:
A x,y;
Vector2() : x(), y() {} // default constructor
Vector2(A xp, A yp){
this->x = xp;
this->y = yp;
}
};
Also, you have typo, should be Point1, Point2 instead of point1/point2.
class rayToCast {
public:
rayToCast(B angle, Vector2<A> origin, Vector2<A> point1, Vector2<A> point2){
this->RAngle = angle;
this->Point1 = point1;
this->Point2 = point2;
}
private:
B RAngle;
Vector2<A> Point1; // capital P
Vector2<A> Point2; // capital P
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With