A method using different flavors of it's own private members
class A{
private:
std::vector<class X> flavor1
std::vector<class X> flavor2
public:
void useVectorOfX(std::vector<class X> someflavor){
... // same logic for both flavors
}
}
Now I want to call useVectorOfX()
from another class, giving it either flavor1
or flavor2
depending on need. I can think开发者_Go百科 of three ways -
Way 1: Use Getter Methods; but it seems unnatural for class A
to get its own data through a Getter Method.
class B{
public:
A *a = new A();
a->useVectorOfX(a->getFlavor1());
}
Way 2: Make the two vectors public
(dirty)
Way 3: Separate Methods?
class B{
public:
A *a = new A();
a->useVectorOfXForFlavor1();
a->useVectorOfXForFlavor2();
}
What about way 1 in a more descriptive format:
class A {
public:
enum {
flavor1 = 0, // used as array index, first element must be zero
flavor2,
} vector_flavor;
static const int number_of_flavors = 2;
void useVectorOfX(vector_flavor flav){
std::vector<class X> someflavor& = vectors[flav];
// ...
}
private:
std::vector<class X> vectors[number_of_flavors];
}
A object; // lol
object.useVectorOfX(A::flavor1);
I would go for option 3. Using
void useVectorOfXForFlavor1(){
useVectorOfX(flavor1);
}
seems perfectly reasonable.
What about something like:
std::vector<class X> flavors[2];
...
public:
void useVectorOf(int X) { useVectorOf(flavors[X]); }
private:
void useVectorOf(std::vector<class X> &v) { ...; }
Using an enum
rather than a plain int
would be nicer.
use
class B{
public:
A *a = new A();
a->useVectorOfX(a->getFlavor1());
}
this is better because you create only one method and and you dont decrare members of the class public unnecessarily.
You've got all the technically correct answers, but the real issue here is the interface design, so I'd like to address that.
First, passing object's own private data as a parameter it its own method is ... well, bizarre, to say the least. Seems that you are trying to solve a low-level issue by exposing your internal implementation details to the user, and making him dependent on any internal changes.
My first question would be "is the useVectorOfX
method really designed to work on any vector<X>
?
yes: you probably should have 2 methods,
doSomething(const vector<X>& clientsData)
anddoSomething() // using your private data
no: second question: "is this (semantically, from user's perspective, not code-wise) the same operation"?
- yes: use one method with modifier, as per @nightcracker, e.g.
doSomething(A::highPrecision)
- no: use 2 methods as per @Bo. This will allow you to change the internal implementation in the future in a user-transparent way
- yes: use one method with modifier, as per @nightcracker, e.g.
精彩评论