C ++实例初始化语法 [英] C++ Instance Initialization Syntax

查看:167
本文介绍了C ++实例初始化语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定类:

class Foo {
public:
    Foo(int);

    Foo(const Foo&);

    Foo& operator=(int);

private:
    // ...
};

这两行是完全相同的,还是它们之间有微妙的区别?

Are these two lines exactly equivalent, or is there a subtle difference between them?

Foo f(42);

Foo f = 42;


我通过使Foo构造函数在原始问题中明确而混淆了问题。我已经删除了,但感谢答案。

I confused matters by making the Foo constructor "explicit" in the original question. I've removed that, but appreciate the answers.

我还添加了一个复制构造函数的声明,以表明复制可能不是一个微不足道的操作。

I've also added declaration of a copy constructor, to make it clear that copying may not be a trivial operation.

我真正想知道的是,根据C ++标准,Foo f = 42直接调用Foo(int)构造函数,

What I really want to know is, according to the C++ standard, will "Foo f = 42" directly call the Foo(int) constructor, or is the copy constructor going to be called?

看起来像fasih.ahmed有我正在寻找的答案(除非他错了)。

It looks like fasih.ahmed has the answer I was looking for (unless he's wrong).

推荐答案

Foo f = 42;

此语句将为值'42'创建一个临时对象。

This statement will make a temporary object for the value '42'.

Foo f(42);

此语句将直接赋值,所以减少一个函数调用。

This statement will directly assign the value so one less function call.

这篇关于C ++实例初始化语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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