构造函数的限制函数
Limiting functions of the constructor
请看下面的代码
游戏对象.cpp
#include "GameObject.h"
GameObject::GameObject(void)
{
id = 0;
}
GameObject::GameObject(int i)
{
id = i;
}
GameObject::~GameObject(void)
{
}
游戏对象.h
#pragma once
class GameObject
{
public:
GameObject(void);
GameObject(int);
~GameObject(void);
int id;
};
主.cpp
#include <iostream>
#include "GameObject.h"
using namespace std;
int main()
{
GameObject obj1;
cout << obj1.id << endl;
GameObject obj2(45);
cout << obj2.id << endl;;
system("pause");
return 0;
}
现在,我想确保无法使用默认构造函数定义游戏对象类型的对象。我该怎么做?请帮忙!
您可以将默认构造函数设为私有。
作为示例,通常,当我们实现单例类时,我们将默认构造函数设为私有并提供静态公共"实例"方法。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- makefile对我的名称空间对象/函数/构造函数的不确定引用
- 没有可调用的匹配函数(构造函数),候选函数不同于对给定类型的引用
- C++库制作,隐藏在标头中没有友元的析构函数/构造函数
- 从另一个成员函数/构造函数调用C++构造函数是否执行初始值设定项列表
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读
- std::调用函数时找不到函数构造函数
- 显式调用基类析构函数/构造函数合法吗
- 函数构造函数和nullptr
- 用委托构造函数构造函数
- 虚函数构造函数和调用虚函数时会发生什么
- 一些Qt函数/构造函数参数的内存管理
- 使用for_each或std::transform时,c++函函数构造函数是如何被调用的?
- std函数构造函数初始化