通过向类变量传递引用来初始化它

Initialize class variable by passing a reference to it

本文关键字:引用 初始化 类变量      更新时间:2023-10-16

我有一个非常有趣的C++练习:

这是强加的主要:

int main(void)
{
    Exam e = Exam(&Exam::cheat);
    e.kobayashiMaru = &Exam::start;
    (e.*e.kobayashiMaru)(3);
    Exam::cheat = true;
    if (e.isCheating())
        (e.*e.kobayashiMaru)(4);
    return (0);
} 

这是要求的输出:

[The exam is starting]
3 Klingon vessels appeared out of nowhere.
You lost again.
[The exam is starting]
4 Klingon vessels appeared out of nowhere.
Win !

现在需要创建Exam类来获得正确的输出。以下是我所做的:

class Exam
{
public:
    Exam(bool *_cheat);
    typedef void (Exam::*func)(int);
    void            start(int);
    bool                       isCheating();
    static bool               cheat;
    func                       kobayashiMaru;
};

我遇到了Exam(&Exam::cheat)的问题。到目前为止,我所理解的是Exam取的是它自己的cheat变量的地址。当输入Exam的构造函数时,cheat未初始化。所以对我来说,我会在这里用false初始化它。

Exam::Exam(bool * _cheat)
{
   *_cheat = false;
}

但通过这样做,我得到了Exam(&Exam::cheat)的多重定义。我不确定我的反思,也许有人能启发我这里到底发生了什么吗?

更改:

static bool cheat;

至:

bool cheat;

Exam类中,允许每个新对象用自己的值处理自己的cheat变量。

构造函数将根据给定值初始化cheat变量,同时使用如下构造函数创建新对象:

Exam::Exam(bool isCheating)
{
   this->cheat = isCheating;
}

或者,如果您想在默认情况下将cheat变量初始化为false/true,您可以制作这样的构造函数:

Exam::Exam()
{
   cheat = false;
   //or cheat = true;
}

您也可以处理多个构造函数。

现在要从Exam类创建新对象,请使用:

Exam *exam1 = new Exam(true); //Will initialize cheat as false
Exam *exam2 = new Exam(false); //Will initialize cheat variable as true

然后访问exam1和exam2对象中的方法,如下所示:

exam1->methodName(1243);
exam2->secondMethodName(true);
exam2->thirdMethodName();
exam3->addFriend(&exam1);

这些只是例子。

希望我能理解你的问题

您有一些问题(在下面的评论中描述)

class Exam
{
public:
    // If cheat is supposed to be a member variable assigned to each instance, passing a pointer to itself is silly and unnecessary
    // If cheat is supposed to be shared between all instances of exam, passing a pointer to itself is silly and unnecessary
    Exam(bool *_cheat);
    static bool               cheat;

    // these two declarations are unnecessary.  They do nothing but add complexity where it is not needed
    typedef void (Exam::*func)(int); 
    func                       kobayashiMaru;
    void            start(int);
    bool                       isCheating();
};

我遇到了考试的问题。我到目前为止的理解是,Exam正在获取自己作弊者的地址变量当进入考试的构造函数时,作弊是未初始化的。所以对我来说,我会在这里用false初始化它。

静态变量在创建类的第一个实例之前进行初始化。问题有两个方面:1)您没有初始化静态成员变量,2)您没有将其视为静态成员变量。

将变量声明为static意味着它将在类的所有实例之间共享(例如,cheat将有一个内存位置)。除非你想让每个服用Exam的人在一个人作弊时就作弊,否则这不太可能是你想要的。

要修复它,您需要Exam类看起来更像这样:

class Exam
{
public:
    Exam(bool cheat) : m_cheat(cheat) {}
    // don't expose member variables directly - use accessor functions
    void setCheating(bool cheat) { m_cheat = cheat; }
    bool isCheating() const { return m_cheat; }
    void start(int);
private:
    bool               m_cheat;
};

main功能的相应更改

int main(void)
{
    Exam e(false);
    e.start(3);
    e.setCheating(true);
    if (e.isCheating())
        e.start(4);
    return 0;
}