开发者

One Method to be seen throughout the entire Project

开发者 https://www.devze.com 2023-02-11 19:48 出处:网络
I have a quest开发者_StackOverflow中文版ion. I have a randomnumber function that I want to be available to all my classes.

I have a quest开发者_StackOverflow中文版ion. I have a randomnumber function that I want to be available to all my classes.

In main,

I have the function

int RandomRange(int min, int max)
{
    int newValue = (rand() % max) + min;

    if ( newValue > max )
        newValue = max;
    if ( newValue < min ) 
        newValue = min;

    return newValue;
}

But I want my classes to be able to use this function. How do I go about something like that?


Create a header:

#ifndef RANDOM_RANGE_H_INLCUDED_
#define RANDOM_RANGE_H_INLCUDED_

int RandomRange(int, int);

#endif

Then include that header in any file that needs to use the function.

When you have time, you might want to write a better implementation of the function.


Declare it as a free-standing function in a header file, and then #include it from everywhere?


The answers saying "put just a declaration in a header file" are right, but it's also worth knowing that you can avoid a separate source file for the definition, and linking the corresponding .o file, by putting this this in a header file:

inline int RandomRange(int min, int max)
{
    int newValue = (rand() % max) + min;
    // etc...
}

This is simpler, but means that every source file that includes the file will have to process the full definition when it's compiled, and also that every source file that includes this file will have to process <cstdlib>, which this file needs to include in order to call rand().

For such a small function and for a header as basic as <cstdlib>, it's premature optimization to worry about the effects of that on compilation time for a full build, although it will noticeably affect partial builds when this header file is changed. There are also some issues of functionality, though - if you do this then:

(a) object files that used this header file and are linked together must use identical definitions of RandomRange, so a change to the contents of the function body breaks link-compatibility. And that's identical after pre-processing - there are no macros used in this example so it's the same either way, but it's possible to make mistakes here.

(b) you can't replace the definition of RandomRange just by linking a different object file containing a different definition (for debugging, testing, or link-time application configurability).

For small functions and small projects, these drawbacks aren't normally a concern. For large functions and large projects, normally at least some of them are, which is why the standard safe thing is to have separate declarations and definitions.

0

精彩评论

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

关注公众号