在构造函数中初始化一个 const 字段,但首先检查一个参数
Initialize a const field in constructor but first check one parameter
好的,这就是我的测试任务。
您需要创建一个 class 具有 const int userID 的用户,以便每个用户对象都有一个唯一的 ID。
我被要求用 2 个参数重载构造函数:键、名称。如果密钥为 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。
有什么想法吗?
可以使用ternary operator,这样就可以在构造函数初始化列表中直接调用:
class User
{
private:
static int nbUsers;
const int userID;
char* name;
public:
User(int key, char* name) : userID(key == 0 ? -1 : nbUsers++)
{
// ...
}
};
standard guarantees that only one of the branches will be evaluated,所以如果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 具有 const int userID 的用户,以便每个用户对象都有一个唯一的 ID。
我被要求用 2 个参数重载构造函数:键、名称。如果密钥为 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。 有什么想法吗?
可以使用ternary operator,这样就可以在构造函数初始化列表中直接调用:
class User
{
private:
static int nbUsers;
const int userID;
char* name;
public:
User(int key, char* name) : userID(key == 0 ? -1 : nbUsers++)
{
// ...
}
};
standard guarantees that only one of the branches will be evaluated,所以如果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))
{
// ...
}
};