是否可以将成员变量作为参数传递给C ++中的成员函数?

时间:2012-04-01 04:48:35

标签: c++

我的工作任务中也有类似的设计问题。我有像

这样的基类
class base
{
protected:
  update()
  {
    // do some stuff with a and b, call it as action A 
  }

  int a, b;
};

class derived : public base
{
protected:
  update()
  {
    // want to do the same action A , but with varaiables c and d
  } 

  int c, d;
};

并且要求是,派生类需要两个操作,例如对“a和b”和“c和d”的操作。因此,设计像update(int,int)这样的方法是可以的,这样我就可以在需要时传递参数“a和b”和“c和d”并对它们执行操作。我知道我可以编写一个帮助方法来执行该操作,但此操作特定于此类,我无法将其与此分开。我还有其他更好的选择。

实时它是一个更大的类而且动作也不是整数,它依次对某些对象,而varibales应该与该类相关。

4 个答案:

答案 0 :(得分:3)

您可以从派生类实现中调用基类实现。只需致电base::update()即可。例如,查看here

答案 1 :(得分:2)

是的,这完全有效:

class base
{
protected:
  void update()
//^^^^   You forgot the return type.
  {
      doUpdate(a, b);
  }
  void doUpdate(int& x, int& y)
  {
    // do some stuff with x and y
    // Because x and y are passed by reference they affect the original values. 
  }
private: // Should probaly make the member vars private
  int a, b;
};

class derived : public base
{
protected:
  void update()
//^^^^   You forgot the return type.
  {
     doUpdate(c, d);
  } 
private: // Should probaly make the member vars private    
  int c, d;
};

答案 2 :(得分:1)

我会重温您的class derived是否有is-a关系(如您所示)或has-a关系,如下所示:

class contains
{
protected:
    base x, y;
    update() { x.update(); y.update(); }
};

答案 3 :(得分:1)

您所要求的是技术上可行的,只需定义

即可
void update(int& a, int &b) 

并在update内部忘记了类memebrs,并始终参考参数并将其称为 update(a,b)update(c,d)

这里要点是理解update是否真的是一个成员函数(还需要访问其他成员变量)或者只是一个静态成员(留在类空间中,但看不到类成员本身)以及类之间的关系是否正确(这仅仅意味着嵌入与继承)。但是这些方面应该基于考虑而不仅仅是单个呼叫相关的......