Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 初始化构造函数中的常量字段,但首先检查一个参数_C++_Constructor_Constants_Unique Id - Fatal编程技术网

C++ 初始化构造函数中的常量字段,但首先检查一个参数

C++ 初始化构造函数中的常量字段,但首先检查一个参数,c++,constructor,constants,unique-id,C++,Constructor,Constants,Unique Id,好吧,这是我测试时的任务。 您需要创建一个具有const int userID的类用户,以便每个用户对象都有一个唯一的ID 我被要求用两个参数重载构造函数:key,name。如果密钥为0,则用户将具有唯一的ID,否则用户将获得userID=-1 我已经做到了: class User{ private: static int nbUsers; const int userID; char* name; public: User(int key, char* name

好吧,这是我测试时的任务。 您需要创建一个具有const int userID的类用户,以便每个用户对象都有一个唯一的ID

我被要求用两个参数重载构造函数:key,name。如果密钥为0,则用户将具有唯一的ID,否则用户将获得userID=-1

我已经做到了:

class User{
private:
    static int nbUsers;
    const int userID;
    char* name;
public:
    User(int key, char* name) :userID(nbUsers++){
        if (name != NULL){
            this->name = new char[strlen(name) + 1];
            strcpy(this->name);
        }
    }
})

我不知道如何先检查key参数是否为0,然后初始化const userID。 有什么想法吗?

您可以使用,以便可以在构造函数初始化列表中直接调用:

class User
{
private:
    static int nbUsers;
    const int userID;
    char* name;

public:
    User(int key, char* name) : userID(key == 0 ? -1 : nbUsers++)
    {
        // ...
    }
};
因此,如果
key==0
,则不会增加
nbUsers


或者,您可以使用辅助功能:

int initDependingOnKey(int key, int& nbUsers)
{
    if(key == 0) return -1;
    return nbUsers++;
}

class User
{
private:
    static int nbUsers;
    const int userID;
    char* name;

public:
    User(int key, char* name) : userID(initDependingOnKey(key, nbUsers))
    {
        // ...
    }
};
可以使用,以便可以在构造函数初始化列表中直接调用:

class User
{
private:
    static int nbUsers;
    const int userID;
    char* name;

public:
    User(int key, char* name) : userID(key == 0 ? -1 : nbUsers++)
    {
        // ...
    }
};
因此,如果
key==0
,则不会增加
nbUsers


或者,您可以使用辅助功能:

int initDependingOnKey(int key, int& nbUsers)
{
    if(key == 0) return -1;
    return nbUsers++;
}

class User
{
private:
    static int nbUsers;
    const int userID;
    char* name;

public:
    User(int key, char* name) : userID(initDependingOnKey(key, nbUsers))
    {
        // ...
    }
};

向上投票,但我更喜欢
key?nbUsers++:-1
。还可以考虑使用
static std::atomic ubUsers
initdependinngonkey
作为
User
类的静态函数更好!向上投票,但我更喜欢
key?nbUsers++:-1
。还可以考虑使用
static std::atomic ubUsers
initdependinngonkey
作为
User
类的静态函数更好!