English 中文(简体)
C+++ 在类成员项目中通过成员函数
原标题:C++ passing in a class member item to a member function

将成员项目不必要地转给成员职能会产生什么后果(但守则不完善):

struct foobar
{
  char * arr; //properly initialized to SIZE at some point
}

class foo
{
  public:
    void bar(foobar&);
    foobar barfoo;
};


void foo::bar(foobar& barf)
{
    cin.get(barf.arr, SIZE,  
 );
    cin.ignore(100,  
 );
}

是否有理由不完全删除 bar 中的参数,直接拨打 barfoo ?不这样做有什么后果,如果有的话?

最佳回答

过过参数时有略微的间接覆盖, 所以如果您永远也不会使用另一个成员来调用这个方法, 那么您就可以摆脱这个参数。 如果您将来可能需要做类似的事情 :

class foo 
{ 
  public: 
    void bar(foobar&); 

  private/*(or still public)*/: 
    foobar barfoo;
    foobar barfoo2;

    void some_other_method() {
      //do stuff
      bar(barfoo);
      bar(barfoo2);
}; 

然后我会离开它独自一人。

问题回答

要看情况了

如果只有 foo::bar 才被调用是当 This-gt;barfoo 作为参数被通过时,那么这很愚蠢(虽然不是明显有害)。

但是,在 this-gt;barfoo 不是可传递到成员函数的唯一参数的情况下,显然它很好。

一种后果是,其他法奥巴的情况不能转而采用同一方法。

问题不在于某一成员是否有时被送往某种方法,而在于是否适宜让打电话者能够指定参数。

由于这是一种公共方法,因此可能还有其他人打电话来,但这一类除外。

没有理由不删除它。至少当您在函数中通过它时,你将做一个额外的特写。

但是,如果某位人物在课外使用bar (foobar&), 您可以在课外超载, 并做类似的事情 :

class foo {
public:
    void bar(); /* Uses default barfoo */
    void bar(foobar&);
    foobar barfoo; 
private:
};

viod foo:bar() {
     bar(barfoo);
}

void foo::bar(foobar& barf) {
    cin.get(barf.arr, SIZE,  
 );
    cin.ignore(100,  
 ); 
} 




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签