构造函数的限制函数

Limiting functions of the constructor

本文关键字:函数 构造函数      更新时间:2023-10-16

请看下面的代码

游戏对象.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;
}

现在,我想确保无法使用默认构造函数定义游戏对象类型的对象。我该怎么做?请帮忙!

您可以将默认构造函数设为私有。

作为示例,通常,当我们实现单例类时,我们将默认构造函数设为私有并提供静态公共"实例"方法。