为什么有人为类提供一个空的默认构造函数? [英] Why would someone provide an empty default constructor for a class?

查看:139
本文介绍了为什么有人为类提供一个空的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class complex
{
  float x,y;
public:
  complex(){} //constructor with no arguments //what is use of giving such constructor
    complex(float z){x=y=z;}//constructor with 1 argument.
    complex(float real,float imag)
    {x=real;y=imag;}
    friend complex sum(complex,complex);
     friend void show(complex);
};

complex sum(complex c1,complex c2)
{
  complex c3;
  c3.x=c1.x+c2.x;
  c3.y=c1.y+c2.y;
  return (c3);
}

void show (complex c)
{
  cout<<c.x<<"+j"<<c.y<<"\n";
}
int main()
{
  complex p,q,r;
  p=complex(2.5,3.9);
  q=complex(1.6,2.5);
  r=sum(p,q);

  cout<<"p=";show(p);
  cout<<"q=";show(q);
  cout<<"r=";show(r);
  return 0;
}


推荐答案

任何构造函数,编译器提供默认构造函数(按需),默认初始化成员。 (注意,内置函数的默认初始化,如 float 什么都不做)。但是,一旦为类定义了任何构造函数,则不再自动提供默认构造函数。因此,如果你还想要一个默认构造函数,你必须定义它。

When you declare a class without any constructors, the compiler provides a default constructor (on demand) that default-initializes the members. (Note that default-initialization on built-ins such as float does nothing). However, once you define any constructor for the class, the default constructor is no longer automatically provided. Hence you must define your own default constructor if you still want one.

这篇关于为什么有人为类提供一个空的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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