Originally Posted by
baxy
ok so if i have a method that formats some private data structures , let say a simple array . and i want to use the same function on a compleatly unrelated class to do the same thing on a private array in that class how would i do this.
It sounds like what you want is a superclass. Then you can put the similar function into the superclass or if it changes based on the subclasses, let them each have their own version. Going on your example here is one that should give some ideas
Code:
class Sup {
protected:
static const int lim_ = 10;
int array_[lim_];
public:
virtual void modif() = 0;
void fill(int i) {
for (int j=0; j < lim_; j++) {
array_[j] = i;
}
}
friend std::ostream & ::print(std::ostream &, const Sup &);
};
std::ostream &print(std::ostream &os, const Sup &s)
{
using std::cout;
cout << s.array_[0];
for (int i = 1; i < s.lim_; i++) {
cout << " " << s.array_[i];
}
return os;
}
class X : public Sup {
private:
const int modifchar_ = 42;
public:
X(int i=0) {
fill(i);
}
~X() { }
virtual void modif() {
for (int i=0; i < lim_; i++) {
array_[i] = modifchar_;
}
}
};
class Y : public Sup {
private:
const int modifchar_ = 97;
public:
Y(int i=0) {
fill(i);
}
~Y() { }
virtual void modif() {
for (int i=0; i < lim_; i++) {
array_[i] = modifchar_;
}
}
};
Demonstration using the classes
Code:
int main()
{
X x;
Y y;
x.fill(10);
y.fill(20);
print(cout, x) << endl;
print(cout, y) << endl;
x.modif();
y.modif();
print(cout, x) << endl;
print(cout, y) << endl;
return 0;
}