如何创建具有不同字符数组的多个类实例?

How can I create multiple class instances with different character arrays?

本文关键字:数组 字符 实例 何创建 创建      更新时间:2023-10-16

我正在尝试为对象的每个实例创建单独的值。此时,我可以为 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。