-
Class Problem
I am not sure how to ask this but here it goes; Lets say I have a class:
Code:
class FILE
{
public:
std::string sName;
};
Then I use it:
Code:
FILE f1;
FILE f2;
f1.sName = "Test.txt";
f2.sName = "Test2.txt";
What I want is to check and make sure this doesnt happen. I want to ensure that each class has a unique sName. So how can I check or ensure this doesnt happen?
-
here's one way
(general outline)
Code:
class FILE
{
private:
static vector<FILE&> myFILES;
string sName;
public:
FILE()
{
myFILES.push_back(*this);
};
~FILE()
{
// remove (*this) from myFILES
};
bool SetName(const string &s)
{
if ( a FILE exists in the vector with the name s)
return false;
sName = s;
return true;
}
};
-
Thanks Sunburnt
I had thought of that I just was wondering if there is an easier and less memory intensive then doing it that way. Seems like there should be a way to access the other classess instances.
Worse case I might just do it that way.
-
There is none, not really. It wouldn't make sense: it would cost large amounts of memory (because the compiler would have to do what sunburnt is doing) and be hardly used.
A way to save some time is to make every class directly a linked list node:
Code:
class FILE
{
private:
static FILE *pFirst; // Initialize to 0
FILE *pNext, pPrev;
string sName;
public:
FILE()
{
if(pFirst) {
pFirst->pPrev = this;
pNext = pFirst;
} else {
pNext = 0;
}
pPrev = 0;
pFirst = this;
};
~FILE()
{
if(pNext) {
pNext->pPrev = pPrev;
}
if(pPrev) {
pPrev->pNext = pNext;
} else {
pFirst = pNext;
}
};
bool SetName(const string &s)
{
if ( a FILE exists in the list with the name s)
return false;
sName = s;
return true;
}
};
You can trade construction speed for SetName speed by using a balanced search tree (e.g. std::set) instead of a list. You'd have to write your own sorting predicate though.
-
Yeah to much work for what I am doing. I just figured if there was a way to safely and maybe quickly do it, I would put it in. Thanks everyone.
POST - 900 :thumb: :bigyello:
PS - Thanks Sunburnt for your MP3 script link, its much better than the other one. ;)