【问题标题】:Using pointers to output values使用指向输出值的指针
【发布时间】: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


【解决方案1】:

C++ 很少需要使用正确的 OO 设计的指针。在您提供的示例中,您可以使用引用而不是指针。此外,如果您操作一个对象,请使用正确的类作为参数而不是 void * 例如

int extract_x(const Thing &thing)
{
   // --- Begin your code ---
   return 0;
   // --- End your code   ---
}

你也可以定义getX()和getY()公共方法,设置foo和bar为public

int Thing::getX(void) const
{
   return x;
}

【讨论】:

  • 好的,我会查找参考我已经看到了一些,问题说我应该能够做我需要的所有事情,只需将代码放在列出的区域中,所以我必须保留函数他们的样子。谢谢你给我参考思路。不想为我解决问题,但我从视觉上学习,所以没有例子很难理解。我会让你们知道我从使用参考中得到了什么。
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2012-03-23
相关资源
最近更新 更多