简体   繁体   中英

C++ - .h and .cpp

If I have a .h file that contains the following for example:

class A
{
...
}

Notice that there is no customized constructor here.

Now, in the .cpp file, can I write the following:

A
{
...
}

In other words, is it ok not to use a constructor after the class name as follows?

A::A()
{
...
}

Thanks.

If your question is whether or not you can use A{} to define a constructor, no, you need to use A::A(){...} syntax for the constructor if you are defining it in the cpp file.

If you are asking if you don't need a constructor, no, you don't necessarily need one, the compiler will supply you with a default.

I should say that if you are doing the constructor in the class definition you can use A(){...}, such as

class A
{
public:
  A(){}
};

I believe the answer to your question is "No". But it's kind of a confusing question. The syntax you propose for the contents of the .cpp file is demonstrably uncompilable.

is it ok not to use a constructor after the class name

As classes get longer and more complicated, mixing the definition and the implementation details makes the class harder to manage and work with.

Traditionally, the class definition is put in a header file of the same name as the class, and the member functions defined outside of the class are put in a .cpp file of the same name as the class.

No. Once you've defined class A like that, the compiler expects A to start one of

A MyObject;
A MyOtherObject = { /* initial values */ }; // C style since there's no ctor
A MyFunction();
A MyFunction() { return MyObject; }

or perhaps a variation like

A* MyPointer;
A& MyReferemce = MyObject;

As you see, the compiler expects you declare something after A . But you have A { . That's just not right: you started a declaration, but you never named what you're declaring.

Yes You Can.If i understood your question correctly.

HEADER FILE

#include < iostream>

using namespace std;

class A{
public:
        A();
        void func();
};

CPP FILE

#include "h.hpp"

using namespace std;

A::A(){cout << "Constructor" << endl;}

int main(){ A a; return 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM