【问题标题】:Please explain the default constructor (int = 10)请解释默认构造函数(int = 10)
【发布时间】:2015-03-08 16:43:56
【问题描述】:
class Array
{
public:

Array(int = 10); // default constructor
~Array(); // destructor

protected:

int size; // number of elements in the Array
int *ptr; // address of dynamically allocated memory
};

有人可以举例说明默认构造函数 (int = 10) 的含义吗?另外,如何创建一个数组类型的新对象并自动为其赋值。

【问题讨论】:

    标签: arrays class constructor operators overloading


    【解决方案1】:

    我会回答您的第一个问题,并希望您进一步了解您将如何解决第二个问题。除非您解决编译问题,否则您将无法获得解决任何其他计算机问题所需的愿景。

    在下面的代码中,

    `Array(int size = 10)` has been written. It means that during construction of the object of class Array, it needs a parameter of `int` type but even if you fail to give the parameter, it would construct the object with `size=10`. This overwrites the "Zero Initialization" behavior to "Default Initialization". 
    

    还有,

    `Array(int=10), Array(int='a')`, these are similar as `Array()`
    

    请找到下面的代码,如果您有任何问题,请告诉我。再次,我希望您自己询问更多关于第二部分的信息。概括你的答案并尝试在谷歌上询问。

    #include <iostream>
    using namespace std;
    
    class Array
    {
    public:
    
    Array(int='a')// default constructor
    {
        this->size = size;
    } 
    ~Array() // destructor
    {
    
    }
    int getSize()
    {
     return size;
    }
    protected:
    
    int size; // number of elements in the Array
    int *ptr; // address of dynamically allocated memory
    };
    
    int main()
    {
        Array one;
        cout<<one.getSize();
        return 0;
    }
    

    希望对你有帮助

    【讨论】:

    • 我还有一个问题。如何使用 += 运算符将一个数组的值合并到另一个数组?
    • 您将不得不重载 += 运算符。起草一个问题并将其提出,或者尝试搜索如何重载运算符。你会找到东西。我很高兴能帮上忙。
    猜你喜欢
    • 2012-06-22
    • 2017-03-02
    • 2016-07-23
    • 2023-03-20
    • 2010-10-30
    • 2014-05-15
    • 2011-03-12
    • 2018-04-23
    相关资源
    最近更新 更多