[英]Passing an array of unknown size to class constructor
I am trying to write a function CycleManager which can hold an array of Cycles.我正在尝试编写一个函数 CycleManager,它可以保存一个 Cycles 数组。 My problem is that I want this class to be able to hold a variable amount of cycles.
我的问题是我希望这个类能够保持可变数量的周期。 This is what I came up with, but it's not working.
这是我想出的,但它不起作用。
Cycle.h循环.h
class Cycle
{
public:
Cycle(std::string name) : name(name) {}
private:
std::string name;
};
CycleManager.h循环管理器.h
#include "Cycle.h"
class CycleManager
{
public:
CycleManager(Cycle (&cycles)[]);
void getCycles();
private:
int currentCycle;
int numberOfCycles;
Cycle (&cycles)[];
};
CycleManager.cpp循环管理器.cpp
CycleManager::CycleManager(Cycle (&cycles)[]) : cycles(cycles), currentCycle(0)
{
numberOfCycles = sizeof(*cycles) / sizeof(Cycle);
}
void CycleManager::getCycles()
{
// Serial.println(this->numberOfCycles);
std::cout << this->numberOfCycles << std::endl;
}
Main.cpp主文件
Cycle cycles[] = {Cycle("Cycle 1"), Cycle("Cycle 2"), Cycle("Cycle 3")};
CycleManager cycleManager(cycles);
int main()
{
cycleManager.getCycles();
return 0;
}
Cycle cycles[] = {Cycle("Cycle 1"), Cycle("Cycle 2"), Cycle("Cycle 3")};
CycleManager cycleManager(cycles);
At this point you know the size of the array.此时您知道数组的大小。 So why not
那为什么不
CycleManager cycleManager(cycles, size);
Adjust constructor appropriately适当调整构造函数
CycleManager(Cycle* cycles, size_t n):cycles(cycles), numberOfCycles(n)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.