[英]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.