c++ - 多个构造函数的内存使用c++

标签 c++ memory memory-management constructor ram

我正在为 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/

相关文章:

c++ - std::min 无法将枚举常量解释为有效整数类型 (g++ 4.6.3)

c++ - 检测整数类型变量的空白输入?

c - C中的变量声明及其内存地址

iphone - 核心数据管理对象属性保留

没有指针的 C++ 多态性

c++ - 如何使用 Boost 预处理器获取类函数可访问的函数列表?

c++ - 递归的权力

iphone - 在 Objective C 中检查内存分配的正确方法

c - malloc 一次,然后在结构数组上分配内存

c - BSS段内存布局