Rob*_*rtS 6 c c++ initialization declaration definition
我想声明多个相同类型的对象,并通过一个表达式用相同的右值初始化它们;无需通过单独的语句声明和初始化它们。
我想要的是这样的:
int a = b = 10; // dummy-statement. This does not work.
Run Code Online (Sandbox Code Playgroud)
或者
int a = int b = 10; // dummy-statement. This does not work either.
Run Code Online (Sandbox Code Playgroud)
代替
int b = 10;
int a = b;
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
从技术上讲,是的:int a = value, b = a;,或者您可能会考虑int a, b = a = value;。没有重复的标识符,不行,至少在 C 中不行;语法根本没有提供它。每个 \xe2\x80\x9d声明符 = 初始值设定项\xe2\x80\x9d 只能声明一个对象,对于 C 2018 6.7.6 1 中的每个语法产生式和 6.7.6 2 中的显式语句: \xe2\x80\x9c每个声明符声明一个标识符\xe2\x80\xa6\xe2\x80\x9d
正如评论中提到的,这是在 C++ 中执行此操作的一种可怕方法。我对 C++\xe2\x80\x99s 中有关单个声明中初始化顺序的规则、有关线程的问题等不做任何陈述。这仅作为教育练习呈现。切勿在生产代码中使用它。
\n\ntemplate<class T> class Sticky\n{\nprivate:\n static T LastInitializer; // To remember last explicit initializer.\n T Value; // Actual value of this object.\n\npublic:\n // Construct from explicit initializer.\n Sticky<T>(T InitialValue) : Value(InitialValue)\n { LastInitializer = InitialValue; }\n\n // Construct without initializer.\n Sticky<T>() : Value(LastInitializer) {}\n\n // Act as a T by returning const and non-const references to the value.\n operator const T &() const { return this->Value; }\n operator T &() { return this->Value; }\n};\n\ntemplate<class T> T Sticky<T>::LastInitializer;\n\n#include <iostream>\n\nint main(void)\n{\n Sticky<int> a = 3, b, c = 15, d;\n\n std::cout << "a = " << a << ".\\n";\n std::cout << "b = " << b << ".\\n";\n std::cout << "c = " << c << ".\\n";\n std::cout << "d = " << d << ".\\n";\n b = 4;\n std::cout << "b = " << b << ".\\n";\n std::cout << "a = " << a << ".\\n";\n}\nRun Code Online (Sandbox Code Playgroud)\n\n输出:
\n\n\na = 3.\nb = 3.\nc = 15.\nd = 15.\nb = 4.\na = 3.\n\n