另一个类中的矢量对象初始化矢量对象并访问矢量对象

时间:2020-02-23 14:11:32

标签: c++ stl

我正在学习c ++初学者水平。 让我们举个例子。 我想知道如何访问另一个类中的vector,以及vector成员的getter和setter用法。

class A{
    int id;
public :
    A(){
    }
    A(int id){
        id=id;
    }
    int get(){
        return id;
    }
    void set(int id1){
        id=id1;
    }

};
class B{
    vector <A> bb1;
}; 

如何为向量bb1创建构造函数,setter和getter。

1 个答案:

答案 0 :(得分:0)

类似于int,但请注意不要复制太多:

class B {
private:
  vector<A> bb1;
public:
  B(vector<A> v) : bb1{std::move(v)} {}
  auto& get_vec() noexcept { return bb1; }
  auto const& get_vec() const noexcept { return bb1; }
  void set_vec(vector<A> v) { bb1 = std::move(v); }
};

要点:

  • noexcept(在此情况下)大致意味着该函数不会抛出。 Further reading
  • const(在此上下文中)表示此功能不会更改对象的状态。 Further reading
  • std::move粗略地说,将一个对象的资源“移动”到另一个对象。通常会为您保存一份副本。当然,std::move比这要复杂得多。 Further reading
相关问题