簡體   English   中英

用向量進行C ++類初始化

[英]C++ class initialization with vector

我繼承了一些我正在尋求擴展的代碼,但是我遇到了一個我之前從未見過的類\\構造函數。 如下所示在代碼段中

class A {
 public:
    A() {};
    ~A() {};
 //protected:
    int value_;

class B: public std::vector<A> {
  public:
    B(int size = 0) :
      std::vector<A>(size)
    {}

所以我收集的是class B class A它是class A class B的向量,可以使用*this語法訪問,因為沒有變量名。 我想在構造函數中啟動class A ,但我不確定如何在此上下文中執行此操作。 我看過這個但是他們已經將向量聲明為一個對象,在這種情況下它是類。

這似乎與正常繼承略有不同,在正常繼承中,我繼承了單個類的許多實例,而在大多數教科書中通常都是一對一的。 我試圖做的是通過class Bclass A構造函數將值傳播到初始化class A 像下面這樣的東西是我嘗試但不編譯的東西。

#include <iostream>
#include <vector>
using namespace std;
class A {
 public:
    A(int int_value) :
    value_(int_value)
    {};
    ~A() {};
 //protected:
    int value_;
};

class B: public vector<A> {
  public:
    B(int size = 0, int a_value) :
      vector<A>(size, A(a_value))
    {};

    vector<int> new_value_;

    void do_something() {
        for (auto& element : *this)
            new_value_.push_back(element.value_);
    }
};

int main() {
    cout << fixed;
    cout << "!!!Begin!!!" << endl;
    B b(20,23);
    cout << b.size() << endl;

    b.do_something();
    for(auto& element : b.new_value_)
        cout << element << endl;

    cout << "finished" << endl;
    system("PAUSE");
    return 0;
}

我想一個后續問題是,這是一個很好的實現這個代碼試圖實現的目標

B(int size = 0, int a_value) ... 

是不正確的。 您可能沒有帶有默認值的參數,后跟沒有默認值的參數。

可能的決議:

  1. 為兩個參數提供默認值。

     B(int size = 0, int a_value = 0) ... 
  2. 僅為第二個參數提供默認值。

     B(int size, int a_value = 0) ... 
  3. 更改,以便它們都沒有默認值。

     B(int size, int a_value) ... 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM