简体   繁体   English

C++ 在同一行中声明多个变量

[英]C++ declaring multiple variables in the same line

I know that declaring variables like this int a = 10, b = 15, c = 20 is possible and it's ok, but is it possible in any program in c++ programming language, to declare variables like this int a, b, c = 10, 15, 20 where a need to be 10 , b need to be 15 and c to be 20 .我知道声明像这样的变量int a = 10, b = 15, c = 20是可能的,这没问题,但是在 C++ 编程语言的任何程序中,是否有可能声明像这样的变量int a, b, c = 10, 15, 20其中a需要是10b需要是15并且c需要是20

Is this possible and is it right way to declare variables like this in c++?这是可能的,在 C++ 中声明这样的变量是正确的方法吗?

EDIT : Is it possible with the overloading operator = ?编辑:重载运算符=是否可能?

The compiler will issue an error for such declarations编译器将针对此类声明发出错误

int a, b, c = 10, 15, 20; 

The only idea that comes to my head is the following :)我脑子里唯一的想法是:)

int a, b, c = ( a = 10, b = 15, 20 ); 

Or you could make these names data members of a structure或者您可以使这些名称成为结构的数据成员

struct { int a, b, c; } s = { 10, 20, 30 };

EDIT: Is it possible with the overloading operator =?编辑:是否可以使用重载运算符 =?

There is not used the copy asssignment operator.没有使用复制赋值运算符。 It is a declaration.这是一个声明。 The copy assignment operator is used with objects that are already defined.:)复制赋值运算符用于已定义的对象。:)

int a, b, c = 10, 15, 20;

is not valid, (and even if it is it would probably initialize c to 20 (with comma operator) and let a and b uninitialized.无效,(即使是它也可能将c初始化为20 (使用逗号运算符)并让ab未初始化。

using c-array/std::array/std::vector may be an option:使用 c-array/std::array/std::vector 可能是一种选择:

int carray[3] = {10, 15, 20};
std::array<int, 3> a = {10, 15, 20};
std::vector<int> v = {10, 15, 20};

now we have carray[0] == a[0] && a[0] == v[0] && v[0] == 10现在我们有carray[0] == a[0] && a[0] == v[0] && v[0] == 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM