我正在为 Nintendo DS(配备 4MB RAM)使用 C++ 编写代码。我制作了一个按钮类来在 UI 中显示按钮 like I described here .为了方便起见,我有四个单独的构造函数。我可以将它们全部压缩成一个构造,但这会很不方便,因为每次构造它时我都需要使用所有参数。我的问题是:
在程序运行时,多个重载的构造函数是否会占用每个对象更多的内存,还是编译器会自动剥离每个对象不需要的其他 3 个不必要的构造函数?
感谢任何帮助。以下是构造函数的参数及其解释:
Button::Button(int x, int y, const char * const label)
{
//Set visibility to true as a default
//Set length to String length
}
Button::Button(int x, int y, const char * const label, bool isVisible)
{
//Set the length to the string length
}
Button::Button(int x, int y, const char * const label, int length)
{
//set visibility to true as a default
}
Button::Button(int x, int y, const char * const label, int length, bool isVisible)
{
//All the variables are specified using constructor
}
最佳答案
虽然我同意其他答案,但减少构造函数的数量不会为您节省任何对象存储成本,您可能应该只是为了方便而这样做。
I could condense all of them into one construct, but it would be inconvenient since I would be required to use all the arguments ever time it is constructed.
不一定非要这样:这就是 default parameters是给。您可以像这样在 header 中对构造函数进行原型(prototype)设计:
class Button {
Button (
int x,
int y,
const char * const label,
int length = -1,
bool isVisible = true
);
注意 =
在最后两个参数之后。这意味着您不必提供这些,如果您不提供,将使用该值。所以:
new Button(1, 2, "hello");
new Button(1, 2, "hello", 5, false);
都很好。您通常定义构造函数,尽管 length
这里的场有点特别;如果它可以取决于 label
的长度或用户提供的值,您需要知道其中的区别。这样在初始化列表中,如果成员字段对应的是length
arg 称为 length
(不是我最喜欢的做法,但在这里没关系):
length (length > 0 ? length : label.length())
length
如果它大于 0,将初始化为用户 arg,默认值为 -1,因此如果未提供该 arg,label.length()
将被使用。
请注意,参数必须按顺序进行,因此您应该考虑最有可能使用的参数。如果在这种情况下您希望指定一个默认参数而不指定另一个,则需要两个构造函数。
关于c++ - 多个构造函数的内存使用c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24532749/