将结构传递给类构造函数

时间:2021-06-15 15:29:41

标签: c++ struct constructor

我需要在类构造函数中初始化结构值,但我不知道将其传递给构造函数的正确方法

我将获取要推送到 data 和 len 中的键和值,然后将其传递给我的构造函数

struct Val{
    std::vector<int> Data;  
    std::vector<int> Len; 
};
class Node {
   public:
    Val value;
    std::vector<std::string> key;               
   
   public:
    Node(std::string key, Val value){
       this->key.push_back(key);
       // code to push value for Data and Len vectors 
    }
    Node(){}
};
int main(){
  std::string key="Hi";
  int d=10;
  int l=5;
  // I need to push these three elements
 // d and l must be pushed to the vectors Data and Len in struct respectively
}

如何将值传递给我的 Node 构造函数,以便我可以对结构中的向量执行 push_back,要推送的值都被找到并存储在一个整数变量中

1 个答案:

答案 0 :(得分:2)

您可以考虑以下方法:

struct Val{
    Val(int d, int len) { // Adding a constructor that takes two ints
        Data.push_back(d); 
        Len.push_back(len);
    }
    std::vector<int> Data;  
    std::vector<int> Len; 
};

class Node {
    Val value;
    std::vector<std::string> key; // Are you sure in this?               
public:
    Node(std::string k, Val val); // Here you define whatever logic you need
    Node() = default; // Defaulted default constructor
};

int main() {
    Node n("foo", Val(21, 42));
}

我对将 vector 用作 some key 有一些疑问。

此外,需要注意的重要事项

Node(std::string key, Val value){
    this->key.push_back(key); 
}

编译器如何区分作为参数的 key 和作为 key 的数据成员的 Nodevalue 的相同问题。

这些参数应该有一些其他的名字,否则它们shadow the data members

关于问题的更新,你应该看看这个实现:

class Node {
    Val value;
    std::vector<std::string> key;               
public:
    Node(std::string k, Val v) : value(v) {
        key.push_back(k);
    }
    Node() = default;
};