Hi. I have this long code and it has a class and inside the class there is a private Point called p1. I am trying to set a double type x to this Point. How do I do that?
1 2 3 4 5 6 7 8 9 10 11 12 13
class Triangle
{
private:
Point p1;
public:
void setPart(constdouble x);
};
void Triangle::setPart(constdouble x)
{
????
}
Um... If you mean you are trying to store x (the parameter) into p1 (your member variable), the syntax would be just a normal assignment operator:
1 2 3 4
void Triangle::setPart(constdouble x)
{
p1 = x; //store x into p1
}
However, p1 is a Point, and x is a double, so I have no way of knowing if that even makes sense; (we would need to see the point class.) For exmaple, if Point represented a point in standard 2D (euclidean) space, then it has two components (x,y). It wouldn't be just one number; it would be two. And so it would be up to the class to explicitly define what assigning it a double value would do:
1 2 3 4 5 6 7
//p1 == (4,6)
p1 = x
//now p1 == (x,6)
// or p1 == (4,x)
// or p1 == (x,x)
// or p1 == (x,0)
// or ERROR, undefined operation...?
One more question, when I did return(t) I get this error: error: conversion from ‘double’ to non-scalar type ‘Point’ requested.
Since I am calling Point Triangle, how do I return the value?
You can return objects just like primitive variables.
Edit: But are you sure it's a Point that you want to return? The name of your method sounds like its purpose is to obtain the value of t. And in the code you've posted, t is a double, not a Point.
What basically I am trying to do is I want to get the value px and add length to it in the Point Triangle :: getT() function. It won't let me return an int or a double so I have to declare a Point but I still don't quiet get the result I want.
1 2 3 4 5 6 7 8
Point Triangle::getT() const
{
Point t;
t = p1.getx() + length;
return(t);
}
You're still not being clear about what you want your method to do. What do you want it to return? Why do you want it to return anything at all? What do you want to do with the thing it's returning? What is the mysterious "T" that it's getting supposed to represent?
OK, so it's supposed to be a Point, then. So, in your method, construct a Point object, set the values in it that you want, and then return it like you would any other variable.
Why give your function such a cryptic name? A well-named method should make it clear what it does, to you and anyone else who is looking at your code. Why not call it GetTopLeftVertex?