C++:避免 .cpp 文件仅包含空(解)构造函数
当我有这样的头文件时:
#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_ */
我需要创建一个像这样的 .cpp
文件:
#include "GameView.h"
GameView::~GameView()
{
}
GameView::GameView()
{
}
这有点愚蠢。只是一个空构造函数和解构函数的 .cpp 文件。 我想简单地在头文件中实现该方法。这样就干净多了。
如何做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以内联定义构造函数和析构函数(这是正确的术语,使用它而不是解构函数):
You can define your constructor and destructor (this is the proper term, use this instead of deconstructor) inline:
就这样吧。
你甚至不需要写这个。编译器本身提供了一个默认构造函数。您唯一需要的是析构函数,因为默认情况下它不是虚拟的。
如果您听说需要在 .cpp 文件中定义它们 - 如果您的类中有智能指针作为成员,有时需要这样做。经验法则是,当您的类中有智能指针,并且它们指向刚刚在标头中前向声明的类时,请始终在实际定义所指向的类的 .cpp 文件中提供构造函数和析构函数。否则,您可能会遇到删除不完整类的问题(在许多情况下导致未定义的行为)。
So be it.
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).
我没有看到你的问题:
当然,如果构造函数不执行任何操作,则无需提供全部内容。
I don't see your problem:
And of course if the constructor does nothing, there is no need to provide it all.