C++: Avoid .cpp files with only an empty (de)const

2019-08-01 15:00发布

问题:

When I have a header file like this:

#ifndef GAMEVIEW_H_
#define GAMEVIEW_H_

#include <SDL/SDL.h>

class GameView
{
public:
 GameView();
 virtual ~GameView();

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};

#endif /* GAMEVIEW_H_ */

I need to create a .cpp file like this:

#include "GameView.h"

GameView::~GameView()
{

}

GameView::GameView()
{
}

This is a bit stupid. Just a .cpp file for an empty constructor and deconstructor. I want to implement that method simply in the header file. That is much cleaner.

How to do this?

回答1:

You can define your constructor and destructor (this is the proper term, use this instead of deconstructor) inline:

class GameView
{
public:
 GameView() {}
 virtual ~GameView() {}

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};


回答2:

I want to implement that method simply in the header file. That is much cleaner.

So be it.

// ...
GameView() { }
virtual ~GameView() { }
// ...

You don't even need to write this. The compiler provides a default constructor itself. The only thing you need is the destructor because it's not virtual by default.

In case you heard you need to define these in the .cpp file - this is sometimes needed if you have smart pointers in your class as members. A rule of thumb is that when you have smart pointers to in your class, and they point to a class that's just forward declared in the header, always provide constructors and destructors in the .cpp file where you actually define the pointed-to class. Otherwise you can get problems with deletion of incomplete classes (causing undefined behavior in many cases).



回答3:

#ifndef GAMEVIEW_H_
#define GAMEVIEW_H_

#include <SDL/SDL.h>

class GameView
{
public:
 GameView() {}
 virtual ~GameView() {}

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};

#endif /* GAMEVIEW_H_ */


回答4:

I don't see your problem:

class GameView
{
public:
 GameView() {}
 virtual ~GameView() {}

 virtual void Update() = 0;
 virtual void Render(SDL_Surface* buffer) = 0;
};

And of course if the constructor does nothing, there is no need to provide it all.