默认构造函数c ++ [英] Default constructor c++

查看:248
本文介绍了默认构造函数c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图理解默认构造函数(由编译器提供,如果你不写一个)与你自己的默认构造函数。这个简单的类:

  class A 
{
private:
int x;
public:
A(){std :: cout<< 默认构造函数调用A \\\
; }
A(int x)
{
std :: cout< 参数构造函数调用A \\\
;
this-> x = x;
}
};

int main(int argc,char const * argv [])
{
A m;
A p(0);
A n();

return 0;
}

输出为:



为A调用的默认构造函数



为A调用的参数构造函数



一个有另一个构造函数调用,我的问题是哪一个和哪个类型在这种情况下有

解决方案

  A n(); 

声明一个名为 n 的函数没有参数,并返回 A



因为它是一个声明,没有代码被调用/执行没有构造函数)。



在声明之后,你可能会写

  A myA = n(); 

这将编译。但它不会链接!因为没有函数 n 的定义。


I am trying to understand how default constructor (provided by the compiler if you do not write one) versus your own default constructor works.

So for example I wrote this simple class:

class A
{
    private:
        int x;
    public:
        A() { std::cout << "Default constructor called for A\n"; }
        A(int x)
        {
            std::cout << "Argument constructor called for A\n";
            this->x = x;
        }
};

int main (int argc, char const *argv[])
{
    A m;
    A p(0);
    A n();

    return 0;
}

The output is :

Default constructor called for A

Argument constructor called for A

So for the last one there is another constructor called and my question is which one and which type does n have in this case?

解决方案

 A n();

declares a function, named n, that takes no arguments and returns an A.

Since it is a declaration, no code is invoked/executed (especially no constructor).

After that declaration, you might write something like

A myA = n();

This would compile. But it would not link! Because there is no definition of the function n.

这篇关于默认构造函数c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆