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

2019-08-01 14:29发布

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?

4条回答
SAY GOODBYE
2楼-- · 2019-08-01 15:11

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-01 15:25
#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_ */
查看更多
Summer. ? 凉城
4楼-- · 2019-08-01 15:27

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).

查看更多
Evening l夕情丶
5楼-- · 2019-08-01 15:30

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;
};
查看更多
登录 后发表回答