开发者

getters and setters in class

I am trying to write a program considering that I have a 开发者_如何学JAVAhuge array of objects( conatinng some data such as id, name etc) I have a display menu something like :

1)

display_menu()
{
    vector< CD > CDArray;
    //some statements to display
    switch(choice)
    {
        //case1 , case 2, ...
        case x;
            for(int i=0; i < CDArray.size(); i++)
                CDArray[i].printCD(); //printCD() is a method of class CD
        //default
    }
}

but this would lead to a lot of function call overhead if the vector/array is large making it slow.

2) shall I delare the function printCD() as inline or

3) declare another object to call the function and pass the vector/array by reference like :

display_menu()
{
    vector< CD > CDArray; 
    CD obj; 
    //some statements to display
    switch(choice)
    {
        //case1 , case 2, ...
        case x;
            obj.printCD(CDArray); //CDArray is passed by reference
        //default
    }
}

Is there something wrong with the third approach

what approach would you suggest?


You're over analyzing the problem. Make it readable first, then worry about performance. 99 times out of 100 what you think will be the greatest source of performance bottlenecks is wrong.

Edit:

To actually answer the question, I'd think in terms of object oriented design. Does your CD object need to know how to print itself to the screen? Does it need to know anything about ostreams in general? I think the answer is no. The best way to do this sort of thing in C++ is to either have a helper function which overloads the << operator so that it works with ostreams without forcing the knowledge of which stream your object is being used with or to have a method which returns the string representation of the object so that you don't even need to worry about where the string is going.


The third approach is fine, it's globaly a data-oriented way of doing it and seems appropriate.

BUT :

Here your function don't need to be a member function, it applies to a set of CD objects and don't have a state. So you should make it a static function or a global function.

It would be me I would setup a namespace and a global function :

cdutil::print( CDArray ); 

But that depends a lot on the semantic of the function. Here I'm not sure at all what it means.


I would go for a (static) method in CD (or a template friend function) that knows how to print a collection of CDs, referenced by two iterators begin and end. However, doing so, is only a good idea, if you really really need the speed-up here.


You could "turn around your thinking" and create an accept_visitor method for the CD class and create a visitor object to pass to each CD object. This would give you more flexibility later on in your project. For more information, contact the Web and search for "Visitor design pattern".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜