显式分配vs隐式分配 [英] Explicit Assignment vs Implicit Assignment

查看:241
本文介绍了显式分配vs隐式分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一本C ++教程,但它实际上并没有给我带来两者之间的差别(除了语法)。


您还可以在声明时为您的变量赋值。当我们
使用赋值运算符(等于
sign)给变量赋值时,它被称为显式赋值:

  int nValue = 5; //显式赋值

也可以使用隐式赋值赋值给变量:

  int nValue(5); //隐式赋值

即使隐式赋值看起来很像函数调用,
编译器跟踪哪些名称是变量,以及哪些是
函数,以便它们可以正确解析。


$ p

解决方案

第一个是首选类型,如 int ;



例如,如果你定义了一个 class Foo

code>,可以从单个 int

构建

  Foo x(5); 

优先于

  Foo x = 5; 

(当你使用多个参数时, $ c> Foo x = Foo(5,hello); 这是普通的丑,看起来像 operator = 正在调用。 / p>

I'm reading a tutorial for C++ but it didn't actually give me a difference (besides syntax) between the two. Here is a quote from the tutorial.

You can also assign values to your variables upon declaration. When we assign values to a variable using the assignment operator (equals sign), it’s called an explicit assignment:

int nValue = 5; // explicit assignment

You can also assign values to variables using an implicit assignment:

int nValue(5); // implicit assignment

Even though implicit assignments look a lot like function calls, the compiler keeps track of which names are variables and which are functions so that they can be resolved properly.

Is there a difference? Is one more preferred over the other?

解决方案

The first is preferred with primitive types like int; the second with types that have a constructor, because it makes the constructor call explicit.

E.g., if you've defined a class Foo that can be constructed from a single int, then

Foo x(5);

is preferred over

Foo x = 5;

(You need the former syntax anyway when more than one argument is passed, unless you use Foo x = Foo(5, "hello"); which is plain ugly and looks like operator= is being called.)

这篇关于显式分配vs隐式分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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