我有一个非常有趣和有趣的C++练习:
这是强制的main:
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)
的多重定义。我不确定我的倒影,也许有人能告诉我这里到底发生了什么?
发布于 2015-12-30 00:11:05
更改:
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);
这些只是一些例子。
希望我能理解你的问题。:)
发布于 2015-12-31 01:11:17
你有几个问题(在下面的评论中描述)
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
的内存位置)。除非你想让每个使用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;
}
https://stackoverflow.com/questions/34514148
复制相似问题