C++中创建对象时三种方式与构造函数

#include <iostream>
using namespace std;

class complax
{
public:
    complax(double r=0,double i=0)
    :re(r),im(i)
    {cout<<"create function with parms"<<endl;}
    double real()const{return re;}
    double imag()const{return im;}
private:
    double re,im;
};

int main() {
    complax c1();
    cout<<"~~~~~~~~"<<endl;
    complax c3;
    cout<<"~!!!!!!!!!"<<endl;
    complax* c2 = new complax();
    return 0;
}

输出:

C:\Users\12431\CLionProjects\untitled\cmake-build-debug\untitled.exe
~~~~~~~~
create function with parms
~!!!!!!!!!
create function with parms

Process finished with exit code 0

 三种构造方式中,第一种方式不会使用显式构造函数(使用隐藏构造函数),其他两种方式都会使用,且当出现歧义构造函数时候,第一种方式不会报错,而其他两种方式会报错,如下:

#include <iostream>
using namespace std;

class complax
{
public:
    complax(double r=0,double i=0)
    :re(r),im(i)
    {
        cout<<"create function with parms"<<endl;
    }
    complax()
    :re(0),im(0)
    {
        cout<<"不带参数的构造函数"<<endl;
    }
    double real()const{return re;}
    double imag()const{return im;}

private:
    double re,im;
};

int main() {
    complax c1();
    cout<<"~~~~~~~~"<<endl;
    complax c3;
    cout<<"~!!!!!!!!!"<<endl;
    complax* c2 = new complax();
    return 0;
}

报错信息为:

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值