类中对集合成员变量的封装

229 篇文章 2 订阅
73 篇文章 0 订阅

JAVA:

对于一般的成员变量,对其提供简单的getter/setter封装即可。而对于一个集合类,不能够这样做。

  对于一个简单的成员变量,可以这样:

class Athlete {
  private String name;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  // ......
}

  而如果是一个Set/List/Map或数组,应该:

  [1]初始化这个集合类;

  [2]提供对单个元素的add/remove;

  [3]提供加入另一个集合的方法。如果是基于此初始化,则先保证当前集合无元素;

  [4]对于getter方法,应该返回该集合的只读试图;

  [5]提供当前集合size。

public class Game {
  private Set<Athlete> players = new HashSet<Athlete>();// 1
  public void addPlayer(Athlete one) {// 2
    players.add(one);
  }
  public void removePlayer(Athlete one) {// 2
    players.remove(one);
  }
  public void addPlayers(Set<Athlete> set) {// 3
    Iterator<Athlete> iter = set.iterator();
    while (iter.hasNext())
      addPlayer(iter.next());
  }
  public void initializaPlayers(Set<Athlete> set) {// 3
    if (getAttendNumbers() > 0)
      players.clear();
    players.addAll(set);
  }
  public Set<Athlete> getAllPlayers() {// 4
    return
Collections.unmodifiableSet(players);
  }
  public int getAttendNumbers() {// 5
    return players.size();
  }
}
C#:1、普通集合的方法AsReadOnly返回值是一个集合的引用,但是只读属性,这用一个指向常量的指针(指针常量)很好理解,指针所指对象不一定是常量,但用这个指针(指针常量)去引用的时候,系统就认为是个常量,从而实现只读的效果C++:


I have a class which has a private attribute vector rectVec;

class A {
private:
   vector<Rect> rectVec;
};

My question is how can I return a 'read-only' copy of my Vector? I am thinking of doing this:

class A {
public:
  const vect<Rect>& getRectVec() { return rectVect; }
}

That is the right way, although you'll probably want to make the function const as well.

class A {
public:
  const vect<Rect>& getRectVec() const { return rectVect; }                           
};
This makes it so that people can call getRectVec using a const A object.

I have a class which has a private attribute vector rectVec;

class A {
private:
   vector<Rect> rectVec;
};

My question is how can I return a 'read-only' copy of my Vector? I am thinking of doing this:

class A {
public:
  const vect<Rect>& getRectVec() { return rectVect; }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值