通过C ++中的公共函数分配私有成员值

时间:2016-04-21 19:39:52

标签: c++

我对在C ++中分配私有成员的价值感到有些困惑 据我所知,以下两种设置长度和宽度的方法都应该有效。有什么区别,一种方法是正确的吗?

class Box
{
   public:
      void setlength(double len)
      {
         length = len;
      }
      void setbreadth(double bread)
      {
         this->breadth = bread;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
};

5 个答案:

答案 0 :(得分:4)

两者都是正确的。在类成员函数的主体内,所有类成员都在范围内。 this->是隐含的。因此,当this->breadth显式访问breadth成员时,length中的setlength()会隐式访问this->length

显式访问允许您为参数和成员使用相同的名称:

void setBreadth(double breadth) {
    this->breadth = breadth;
}

在这种情况下,非限定访问引用参数​​,限定访问引用该成员。

答案 1 :(得分:1)

没有区别。它是语法糖。

答案 2 :(得分:0)

除了@Barryanswer之外,我个人更喜欢写一些类似

的内容
class Box
{
   public:
      double length() const { return length_; }
      void length(double length) { length_ = length; }
      double breadth() const { return breadth_; }
      void breadth(double breadth) { breadth_ = breadth; }
   private:
      double length_;     // Length of a box
      double breadth_;    // Breadth of a box
};

避免歧义,并根据重载提供简洁的getter / setter函数名称。

答案 3 :(得分:0)

Using the this pointer is not necessary if the member- and parameter names are different.
It's an explicit way of saying member of this object, whose value is the address of the object.

But, if you don't use the this pointer when the names are equal, you will be assigning the value of the local variable to itself:

void setlength(double length) 
{ // assigning value to itself
    length = length;
} // this->length is unchanged

If the names are the same and you use the this pointer explicitly, you will get the expected result:

void setlength(double length) 
{
    this->length = length;
}

Here we are saying I mean length that belongs to this object

答案 4 :(得分:-1)

巴里简要解释道。 length = len;,其实际行为与this->length = len;相同,因为类方法有一个名为this的隐藏参数,并隐式插入this