开发者

C++ - Namespace vs. Static Functions [duplicate]

开发者 https://www.devze.com 2023-04-12 15:26 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Namespace + functions versus static methods on a class
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Namespace + functions versus static methods on a class

I want to group similar functions togther. I can do it one of two ways. To me they are just syntactical differences...in the end it does not matter. Is this view accurate?

Namespace:

namespace util
  {
  void print_array(int array[])
    {
    int count = sizeof( array ) / sizeof( array[0] );
    for (int i = 0; i <= count; i++) cout << array[i];
    }
  }

Class:

class Util
  {
  public:
    static void print_array(int array[])
      {
      int count = sizeof(array);
      for (int i = 0; i <= count; i++) cout << array[i];
      }
  };

Call with

Util::print_array()  // C开发者_运维知识库lass

or

util::print_array()  // Namespace


The second way is silly and a complete nonsense. Classes are not namespaces, and should never be used as such.

Also, the code is wrong, sizeof(array) won't return what you think.


There are some differences in that the second way allows you to do a couple of (nonsensical) things that the first way does not:

  • Using the second way you can create instances of Util using either Util foo; or Util* foo = new Util();.
  • You can also use Util as a type parameter for templates (or anywhere else where typenames are allowed). So you could e.g. create a vector<Util>.
  • You can also calculate the size of Util instances using sizeof(Util).

Since there's no reason you'd want to be able to do either of those things, you should use the first way. Generally you should almost always rethink using a class when there are no circumstances under which you'd want to instantiate it.

On an unrelated note: In your code sizeof(array) is equivalent to sizeof(int*) and almost certainly doesn't do what you think it does (i.e. it does not tell you how many elements are in the array).

0

精彩评论

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