在同一类中的in构造函数中调用Constructor [英] Calling Constructor with in constructor in same class

查看:221
本文介绍了在同一类中的in构造函数中调用Constructor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原本希望输出2、3,但是我得到的是垃圾值。

I was expecting the output 2, 3 but I'm getting garbage value. Why's that?

这是我的代码:

#include <iostream>
using namespace std;

class A
{
public:
    int a, b;

    A()
    {
        cout << a << " " << b;
    }

    A(int x, int y)
    {
        a = x;
        b = y;
        A(); // calling the default constructor
    }
};

int main()
{
    A ob(2, 3);
    return 0;
}


推荐答案

在此构造函数中:

A(int x, int y)
{
    a = x;
    b = y;
    A(); // calling the default constructor
}

call A() ; 创建一个新的临时对象,该对象在此语句后立即删除。因为默认构造函数 A()不会初始化数据成员 a b 然后输出垃圾。

call A(); creates a new temporary object that is immediately deleted after this statement. Because the default constructor A() does not initializes data members a and b then it outputs a garbage.

此临时对象与构造函数 A(int,int)

This temporary object has nothing common with the object created by constructor A( int, int ).

您可以通过以下方式重写课程:

You could rewrite your class the following way:

class A
{
public:
    int a, b;

    A(): A(0, 0) {}

    A(int x, int y) : a(x), b(y)
    {
        cout << a << " " << b;
    }
};

这篇关于在同一类中的in构造函数中调用Constructor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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