【发布时间】:2017-03-21 02:30:04
【问题描述】:
制作程序输出
// the values of:
//
// * `thing->x`
// * `thing->y`
// * `thing->foo()`
// * `thing->bar()`
using namespace std;
class Thing
{
private:
int x;
int y;
virtual int foo()
{
return x + y;
}
virtual int bar()
{
return x*y;
}
public:
Thing() {
x = 2;
y = 10;
}
};
int extract_x(void *thing)
{
Thing thing;
Thing();
cout << x;
return 0;
}
int extract_y(void *thing)
{
Thing thing;
Thing();
cout << y;
return 0;
// --- End your code ---
}
int call_foo(void *thing)
{
// --- Begin your code ---
return 0;
// --- End your code ---
}
int call_bar(void* thing)
{
// --- Begin your code ---
return 0;
// --- End your code ---
}
int main()
{
Thing thing;
std::printf("%d %d %d %d\n",
extract_x(&thing),
extract_y(&thing),
call_foo(&thing),
call_bar(&thing));
system("pause");
return 0;
}
我在这里尝试创建新对象并获取 Thing 类中的变量,但它仍然不起作用。说 x 是未定义的。除了 extraxt_x、extract_y、call_foo 和 call_bar 的主体,我不应该触摸任何东西
【问题讨论】:
-
“不工作”不是对问题的正确描述。你尝试了什么?你有编译器错误吗?它说了什么?你试过研究它吗? (也许这可能会导致答案)
-
看起来你复制了一个任务,所有东西都放在一个银盘上交给你。完全按照作业告诉你的去做,你不会有问题的。
-
你尝试了什么?鉴于您的问题的性质,您提供的代码看起来不像您尝试过的代码。它看起来非常像作业中的存根代码 - 暗示你没有尝试任何东西(即使答案就在你面前)。
-
我正在尝试练习我认为在这个作业中我们可以返回 thing>x 并返回 thing>y 的指针。当我尝试这个时,它说 x 是未定义的并且 y 也是。在问题中,x 和 y 是公开的,为什么我不能抓住它们,或者我必须做 Thing thing=new Thing 才能访问这些。抱歉,如果这是第一次在这里学习的错误地点。
标签: c++ function pointers function-pointers