繁体   English   中英

c++ 用字符串初始化 class 的字符数组成员

[英]c++ initialize char array member of a class with a string

i have a class which has several members of char arrays, and i want to initialize this class with an array of strings which are the values of the char arrays.

class Product {
public:
    char productId[20];
    char productName[50];
    char price[9];
    char stock[9];

    Product(vector<string> v) : productId(v[0]), productName(v[1]), price(v[2]), stock(v[3]) {  }
};

使用此代码,我收到一条错误消息,指出no suitable conversion function from "str::string" to "char[20]" exist

底部的代码将起作用。 但这是个好主意吗? 可能不是。 您最好将std::string直接存储在您的Product类型中:

#include <cassert>
#include <iostream>
#include <vector>

#include <string.h>

class Product {
public:
  std::string productId;
  ...

  Product(std::vector<std::string> v) : productId{std::move(v[0])} {}
};

但是这段代码有问题; 你在哪里检查向量是否包含所有必需的元素? 最好制作一个接口来指定Product分别由四个字符串组成:

class Product {
public:
  std::string productId;
  ...

  Product(std::string pid, ...) : productId{std::move(pid)}, ... {}
};

但是,如果您坚持 C/C++ 合并;

#include <cassert>
#include <vector>

#include <string.h> // strcpy

class Product {
public:
  char productId[20];
  char productName[50];
  char price[9];
  char stock[9];

  Product(const std::vector<std::string> &v) {
    assert(!v.empty()); // really; v.size() == 4
    ::strcpy(&productId[0], v[0].data());
    // ...etc.
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM