create temporaries using a default constructor

本文探讨了C++中使用默认构造函数创建临时对象时遇到的编译错误,并通过修改构造方式展示了正确的实例化方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Try to compile codes which demonstrate bolew

#include  < iostream >

class  Bar {
public :
    Bar() {}
};

class  Foo {
public :
    Foo(
const  Bar &  b)  {}
    
void  blah() {
        std::cout 
<<   " Foo::blah() called. " ;
    }
};

int  main()
{
    Foo foo(Bar());
    foo.blah();
}

You got an error, aren't you? What's wrong with the codes?

let's changed the codes to:

#include  < iostream >

class  Bar {
public :
    Bar() {}
};

class  Foo {
public :
    Foo(
const  Bar &  b)  {}
    
void  blah() {
        std::cout 
<<   " Foo::blah() called. " ;
    }
};

Bar bar()
{
    
return  Bar();
}

int  main()
{
    Foo foo(Bar());  
// this is just decclare an existence non-member function which param is another non-member functions and return value is Foo, and the Bar() part is the param of funtion fun and it returns Bar() and without any parameters

    Foo  x 
=  foo(bar);
    x.blah();
}
Foo foo(Bar(*pFunc)())
{
    
return Foo(pFunc());
}

So the codes demonstrate why create temporaries using a default constructor can't be compiled.

And it will be ok, when you just initialize Foo using:

Foo x  =  Bar();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值