I have small basic C++ problem i’d like ti have you advice on :
for instance, I am trying to write a small vector class. Here is the code i’d like to use
class Vector{
public :
float x,y,z;
Vector(){
}
Vector(float x1, float y1, float z1) {
x=x1;y=y1;z=z1;
}
normalize() {
float norm = TMath::Sqrt(pow(x,2)+pow(y,2)+pow(z,2));
===> this = new Vector(x/norm, y/norm, z/norm);
}
};
But :
1- this small prog won’t compile with .L porg.C++ because
of the line with =====>. I mean, is there a may to dynamically modify my vector object calling obj->normalize(). Of course i could return the normalized vector and do obj = obj->normalize(), but I’m trying to avoid this
2- if I create a Vector object and do obj->x = NULL, then the test obj->x==NULL returns 1 (OK). But if I creata a void object, for instance v=new Vector(), the test v==NULL returns 0.
I guess the 2 questions are linked. And if I can figure out how dynamically modify my pointer it should be goos, but i tried every combination of & and *, but nothong worked
You seem to be new to C++. I would strongly recommend to read
some introductory book to C++ or read some code playing with classes.
In your case, replace your function
normalize() {
float norm = TMath::Sqrt(pow(x,2)+pow(y,2)+pow(z,2));
===> this = new Vector(x/norm, y/norm, z/norm);
}
by
normalize() {
float norm = TMath::Sqrt(pow(x,2)+pow(y,2)+pow(z,2));
if (norm == 0) return; //or print an error message
x /= norm;
y /= norm;
z /= norm;
}
Rene
well, i was trying to give a simple example to explain my problem. Of course with a vector class you always can do like this. The problem is with a custom linked list class. I used the source code of the ROOT TList class to make a small sigle linked list class, but I don’t think this really matters.
Let’s say I have an object with the default constructor;
Sorry, but I still do not understand what you try to do.
When you call your default constructor, the members are not initialized.
Testing if next is null will give unpredictable results. You should initialize the members to some default values, eg
Thanks for your answer.
The only thing i was trying to do is to debug a program I made and catch the error which occurs in the rare case when the list is void : I made a small read() function which uses the usual algorithm to read the content of a linked list
void read() {
for(List *l = this; l != NULL; l = l->next) {
cout << val << " -> " << endl;
}
So I guess i’ll have to add a protection for the case my list is void (it throws a segm violation if I call l->read() wih a void list for l)