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

时间:2015-12-29 15:33:34

标签: c++ reference

我有一个非常有趣和有趣的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)的多重定义。我不确定我的反思,也许有人可以告诉我这里发生了什么?

2 个答案:

答案 0 :(得分:0)

变化:

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);

那些只是例子。

希望我理解你的问题。 :)

答案 1 :(得分:0)

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

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 :: cheat)的问题。我是什么   到目前为止,我们理解的是,考试正在考虑它自己作弊的地址   变量。进入考试的构造函数时,作弊未初始化。   所以对我来说,我会在这里用false初始化它。

在创建类的第一个实例之前初始化静态变量。您遇到的问题有两个:1)您尚未初始化静态成员变量,2)您并未将其视为静态成员变量。

将变量声明为static意味着它将在类的所有实例之间共享(例如,cheat将有1个内存位置)。除非你希望每个人在{1}}作弊时尽快作弊,否则这不太可能是你想要的。

要修复它,您希望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
相关问题