如何创建具有不同字符数组的多个类实例?
How can I create multiple class instances with different character arrays?
我正在尝试为对象的每个实例创建单独的值。此时,我可以为 3 个实例中的每一个提供单独的 Int 值,但是我无法以相同的方式分配字符数组。
理想情况下,我希望能够在每次创建实例时分配单独的字符数组和整数。
这是我当前的代码
class node{
private:
int unitID;
int plantID;
int M1Thresh;
int M2Thresh;
char nodeName[15];
public:
node(int unitID, char nodeName[15], int plantID, int M1Thresh, int M2Thresh){
this->unitID = unitID;
this->plantID = plantID;
this->nodeName[15] = nodeName;
this->M1Thresh = M1Thresh;
this->M2Thresh = M2Thresh;
}
void Showit(){
// Tried this with no success also
// String outval = nodeName + "/0";
//Serial.print("Test string:");Serial.println(outval);
Serial.print("unit ID: ");Serial.println(unitID);
Serial.print("plant ID: ");Serial.println(plantID);
Serial.print("Name: "); Serial.println(nodeName[15]);
Serial.print("M1Thresh: ");Serial.println(M1Thresh);
Serial.print("M2Thresh: ");Serial.println(M2Thresh);
Serial.println(" ");
}
};
node Strawberries = node(101, "Strawberries", 01, 25, 25);
node Cucumber = node(102, "Cucumber", 02, 50, 50);
node Carrot = node (103, "Carrot", 03, 70, 70);
void setup(){
Serial.begin(9600);
}
void loop(){
Strawberries.Showit();
Cucumber.Showit();
Carrot.Showit();
delay(1000);
}
我希望能够使用单独的 char[] 创建每个实例。
我的整数在打印输出上发送/分配很好,但 char[] 打印没有给我任何东西。
任何帮助为我指出正确的方向,我将不胜感激。
谢谢。
在使用nodeName
时存在一些问题。首先,这种说法是错误的:
this->nodeName[15] = nodeName;
这将为不存在的 (!( 第 16 个字符分配一个值this->nodeName
。是的,我说的是第 16 个字符,而不是第 15 个字符,因为 C++ 中的索引是从 0 开始的(例如,第一个字符是nodeName[0]
个字符,第二个字符是nodeName[1]
个字符,第 15 个字符是nodeName[14]
个字符(。
分配给this->nodeName
的值可能是指向nodeName
的第一个字符的指针,转换为char
,这几乎肯定不是你想要的。如果绝对必须对nodeName
使用字符数组,则可以这样做:
std::strncpy(this->nodeName, nodeName, 15);
this->nodeName[14] = ' '; // Ensuring NUL-termination, even if something
// is wonky with nodeName
但是,我强烈支持uneven_mark的建议,使nodeName
类型为std::string
型,而不是固定长度的字符数组。与strncpy
及其恶魔同伴打交道可能很棘手。
代码中的另一个问题在这里:
Serial.println(nodeName[15]);
同样,这将打印不存在的(!(nodeName
的第 16 个字符。如果你使用字符数组进行nodeName
,那么你应该只写
Serial.println(nodeName);
如果你明智地nodeName
成为一个std::string
,那么你可能需要写
Serial.println(nodeName.c_str());
相反。
回答你的问题(如果我理解正确的话!( nodeName[15] 这意味着访问数组的 16 个字符位置,所以你只打印(我不知道什么是 Serial.print,所以我假设它实际上打印(位置 16 上的字符:
Serial.print("Name: "); Serial.println(nodeName[15]);
这段代码似乎也不对:
this->nodeName[15] = nodeName;
你应该使用 strncpy 或类似的东西:
strncpy(this->nodeName, nodeName, 16);
此外,不能保证 nodeName 适合 16 个字符,因此您应该重新考虑您这样做的方式。
还可以考虑使用 c++ 功能,如 std::sstring。
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符