-
Silly Class Question
How do you create a class where the base object can be assigned a value?
I'd like to do something like:
Code:
class number{
public:
blah blah blah
void increment() {
// Probably something like self++ ???
}
};
int someFunction() {
number val = 100;
val.increment();
return val;
}
I've seen it done enough times but have no clue how to actually implement it.
I guess I could always study the string class . . .
-
First off, you wouldn't be actually incrementing the class. You'd be incrementing some base type that the class contains. Example:
Code:
class Number {
private:
int num;
public:
Number( ) { num = 0; }
void Increment( ) { num++; }
};
Because really, what else would you be incrementing? There has to be something to actually increment.
Quzah.
-
Further clarification
You know how you can do a
Code:
string somestring = "Hello there";
somestring.replace(4, 2, "xx");
I want to know how they are able to do that.
Maybe it's not something you can do with a class . . .
-
the replace function is one that works with strings.
If you wanted to do the same thing with your class, then you would need to write a function that would do that.
Later,
-
The replace function was used just as an example. I guess I'm not explaining it clear enough.
-
Are you just wanting to increment one value held inside of the class?
If so, that is simple.
Create a function ( declared public as part of the class ) that will increment the value that you want.
-
>>I want to know how they are able to do that.
>>Maybe it's not something you can do with a class . . .
You can do anything with a class!
Anyhow, I don't understand your question, so I will leave it at that :)
-
When you use the ANSI string class you can do a 'string stringname="text"'
Using that string you can do things like "stringname.insert(foo)" and "stringname.erase(foo)". Of course foo isn't valid syntax for those commands.
Using classes I know how to do things like:
Code:
class someclass {
public:
int val;
int someotherval;
void somefunction() {}
};
someclass object;
object.val = 10;
object.somefunction();
and so on . . .
What I want to know is how they are able to assign a value to "stringname" without needing to do something like "stringname.val = somevalue".
Hope this clarifies my question a bit.
-
It's called operator overloading. It is a tool that enables you to use more natural syntax for your classes. In essence, it works like this:
Code:
class DoubleNum {
private:
int value1;
int value2;
public:
DoubleNum():value1(0), value2(0){}
void operator = (int this_value) {
value1 = this_value;
value2 = this_value;
}
void print() {
cout << endl << "Value One: " << value1 << endl
<< "Value Two: " << value2 << endl;
}
};
int main()
{
DoubleNum d;
d.print();
d = 12;
d.print();
system("pause");
return 0;
}
-
Thank you!!!! I owe you a beer.