1

Reading code from other posts, I'm seeing something like this.

struct Foo {
  Foo() : mem(0) {}
  int mem;
};

What does mem(0) {} does in this case, especially regarding the curly brackets? I have never seen this before and have no idea where else I would find out about this. I know that mem(0), would intialize mem to 0, but why the {}?

Thanks.

4

3 回答 3

7

Since Foo() is the class' constructor, it must have a body, even if the member variable mem is initialized outside of it.

That's why, in your example, the constructor has an empty body:

Foo() : mem(0)
{
    // 'mem' is already initialized, but a body is still required.
}
于 2012-01-17T10:00:52.167 回答
2

It defines the constructor of the class. The part after the colon is the initialization list, in which the mem member is initialized to zero using a constructor call.

Compare:

int a(0);
int b = 0;

These two do the same, but the former is more in line with how object construction typically looks in C++.

于 2012-01-17T10:00:14.303 回答
0

int c++ 你可以在 .h 文件中定义你的方法实现

class MyClass
{
  public:
   MyClass(){
     .....
   }

   void doSomething(){
     .....
   }

   ~MyClass(){
     .....
   }
};

通常它用于模板实现。如果您想避免库链接,并且您更愿意将所有代码提供给用户,您也可以使用这种类声明方法,这样他就可以包含您的文件,而无需将任何 lib 文件链接到他的项目。

于 2012-01-17T10:05:52.223 回答