- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经在网上搜索了这个问题的答案,但我还没有找到满意的答案。我想知道初始化结构和类类型对象的所有规则是什么,特别是当涉及构造函数与支撑初始化列表时。结构与类的规则也不同吗?
假设我们有一个名为 Rectangle
的类或结构。
#include <iostream>
using namespace std;
class Rectangle {
public:
Rectangle() : x(5.0), y(6.0), width(7.0), height(8.0) {}
void printMe()
{
cout << "The rectangle is located at (" << x << ',' << y << ") and is " << width << " x " << height << endl;
}
double x;
double y;
double width;
double height;
};
int main()
{
Rectangle r = {0.0, 0.0, 3.0, 4.0};
r.printMe();
Rectangle s; // uninitialized!
s.printMe();
}
我尝试按照您通常在 C 中执行的方式初始化 Rectangle r
,使用普通的旧花括号初始化列表。但是,g++
给出了以下错误:
constructor_vs_initializer_list.cpp: In function ‘int main()’:
constructor_vs_initializer_list.cpp:21:38: error: could not convert ‘{0.0, 0.0, 3.0e+0, 4.0e+0}’ from ‘<brace-enclosed initializer list>’ to ‘Rectangle’
Rectangle r = {0.0, 0.0, 3.0, 4.0};
^
嗯……乍一看,这不是很有用的错误信息。但是我认为它与构造函数有关,因为如果我删除它,代码将编译并运行!我认为这将是一个悖论,花括号初始化列表和构造函数都在竞争初始化数据成员。
但是,当我将数据成员设为private
时,在移除构造函数后,即再次显示相同的错误信息!
我想知道数据成员初始化的优先级规则是什么。大括号初始化列表与您自己定义的构造函数相比如何?它与 C++11 特性相比如何:= default
构造函数和类内成员初始值设定项?我假设这些初始化对象数据成员的不同方式会以某种方式相互冲突。
Rectangle() = default;
...
double x = 1.0;
我并不是说将它们混合在一起一定是好的代码,只是它是代码,而且在我看来应该很好理解的代码。谢谢。
最佳答案
这是一个演示差异的示例。 C++ 中的初始化非常复杂。请参阅:https://blog.tartanllama.xyz/initialization-is-bonkers/ .
通常最好使用default member initializers或 initialization lists .您在构造函数中做的是正确的事情。只需使用 direct-list-initialization 调用构造函数或 direct initialization以避免混淆人们。 通常,您只会使用复制列表初始化来初始化聚合,而无需用户提供的构造函数。
#include <iostream>
struct A {
int i;
};
struct B {
B() = default;
int i;
};
struct C {
C();
int i;
};
C::C() = default;
struct D {
D(){};
int i;
};
struct E : public D {
};
struct F {
F(int i = 5) {}
int i;
};
struct G {
G() = delete;
int i;
};
int main() {
// g++ (v 8.2.1) provides good warnings about uninitialized values.
// clang++ (v 7.0.1) does not.
// Technically, they are initialized to 'indeterminate values', but it is
// easier to refer to the member variables as uninitialized.
{
// All of the following are 'default initialized', meaning they are not even
// zero-initialized. Members are UNINITIALIZED (Technically, they are
// initialized to 'indeterminate' values.
// Either nothing is done, or the default constructor is called (in
// which nothing is done).
A a;
B b;
C c;
D d;
E e;
F f;
std::cout << "a: " << a.i << std::endl;
std::cout << "b: " << b.i << std::endl;
std::cout << "c: " << c.i << std::endl;
std::cout << "d: " << d.i << std::endl;
std::cout << "e: " << e.i << std::endl;
std::cout << "f: " << f.i << std::endl;
std::cout << std::endl;
} {
// This is more complex, as these are all 'list initialized'.
// Thank you, infinite wisdom of the C++ committee.
A a{};
// Direct list initialization -> aggregate initialization
// - A has no user-provided constructor and
// thus is an aggregate, and agg. init. takes place.
// This 'value initializes' all *MEMBERS* (unless a default member
// initializer exists, which it does not here).
// Value initialization of non-class types results in
// zero-initialization. (member `i` is zero-initialized)
A a2 = {};
// same thing, but via copy list initialization
A a3{{}};
// recursive, initializes `i` with {}, which zero initializes `i`.
A a4{0};
// recursive, initializes `i` 0;
// Could also do `A a4 = {0}`
A a5{a};
// direct intialization of `a5` with `a`.
// Implicit copy constructor chosen by overload resolution.
A a6{A{}};
// post C++17, direct initializes a6 with a prvalue of type A, that is
// aggregate initialized as above. NOT copy/move initialized, but
// instead initialized via the "initializer expression itself".
// I assume this means the value of a6 is directly set via as if it were
// being aggregate initialized.
B b{};
// Same as A. `B() = default;` does NOT specify a user-provided
// constructor
C c{};
// Because the first declaration of `C()` is not `C() = default;`,
// this DOES have a user-provided constructor, and 'value initializaton'
// is performed.
// NOTE: this value intializes `C`, not the *MEMBERS* of `C`.
// Because `C` is a normal class type, value initialization just calls
// the default constructor, which does nothing, and leaves all members
// uninitialized.
D d{};
// D is a class type that is list/direct initialization -> value
// inititalizaton -> default initialization -> call constructor ->
// members are left unitialized.
E e{};
// List initialization -> value initialization -> default initialization
// -> calls implicitly defined default constructor -> Calls default
// constructor of bases -> leaves E::D.i uninitialized
F f{};
// List/direct initialization -> value initialization -> calls default
// constructor with default arguments -> leaves F.i uninitialized
// G g{};
// Fails to compile.
// list initialization -> value initialization -> default initialization
// -> deleted default constructor selected by overload resolution ->
// fails to compile
std::cout << "a: " << a.i << std::endl;
std::cout << "a2: " << a2.i << std::endl;
std::cout << "a3: " << a3.i << std::endl;
std::cout << "a4: " << a4.i << std::endl;
std::cout << "a5: " << a5.i << std::endl;
std::cout << "a6: " << a6.i << std::endl;
std::cout << "b: " << b.i << std::endl;
std::cout << "c: " << c.i << std::endl;
std::cout << "d: " << d.i << std::endl;
std::cout << "e: " << e.i << std::endl;
std::cout << "f: " << f.i << std::endl;
}
}
关于c++ - 使用构造函数与大括号初始化列表来初始化类和结构的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53983280/
C语言sscanf()函数:从字符串中读取指定格式的数据 头文件: ?
最近,我有一个关于工作预评估的问题,即使查询了每个功能的工作原理,我也不知道如何解决。这是一个伪代码。 下面是一个名为foo()的函数,该函数将被传递一个值并返回一个值。如果将以下值传递给foo函数,
CStr 函数 返回表达式,该表达式已被转换为 String 子类型的 Variant。 CStr(expression) expression 参数是任意有效的表达式。 说明 通常,可以
CSng 函数 返回表达式,该表达式已被转换为 Single 子类型的 Variant。 CSng(expression) expression 参数是任意有效的表达式。 说明 通常,可
CreateObject 函数 创建并返回对 Automation 对象的引用。 CreateObject(servername.typename [, location]) 参数 serv
Cos 函数 返回某个角的余弦值。 Cos(number) number 参数可以是任何将某个角表示为弧度的有效数值表达式。 说明 Cos 函数取某个角并返回直角三角形两边的比值。此比值是
CLng 函数 返回表达式,此表达式已被转换为 Long 子类型的 Variant。 CLng(expression) expression 参数是任意有效的表达式。 说明 通常,您可以使
CInt 函数 返回表达式,此表达式已被转换为 Integer 子类型的 Variant。 CInt(expression) expression 参数是任意有效的表达式。 说明 通常,可
Chr 函数 返回与指定的 ANSI 字符代码相对应的字符。 Chr(charcode) charcode 参数是可以标识字符的数字。 说明 从 0 到 31 的数字表示标准的不可打印的
CDbl 函数 返回表达式,此表达式已被转换为 Double 子类型的 Variant。 CDbl(expression) expression 参数是任意有效的表达式。 说明 通常,您可
CDate 函数 返回表达式,此表达式已被转换为 Date 子类型的 Variant。 CDate(date) date 参数是任意有效的日期表达式。 说明 IsDate 函数用于判断 d
CCur 函数 返回表达式,此表达式已被转换为 Currency 子类型的 Variant。 CCur(expression) expression 参数是任意有效的表达式。 说明 通常,
CByte 函数 返回表达式,此表达式已被转换为 Byte 子类型的 Variant。 CByte(expression) expression 参数是任意有效的表达式。 说明 通常,可以
CBool 函数 返回表达式,此表达式已转换为 Boolean 子类型的 Variant。 CBool(expression) expression 是任意有效的表达式。 说明 如果 ex
Atn 函数 返回数值的反正切值。 Atn(number) number 参数可以是任意有效的数值表达式。 说明 Atn 函数计算直角三角形两个边的比值 (number) 并返回对应角的弧
Asc 函数 返回与字符串的第一个字母对应的 ANSI 字符代码。 Asc(string) string 参数是任意有效的字符串表达式。如果 string 参数未包含字符,则将发生运行时错误。
Array 函数 返回包含数组的 Variant。 Array(arglist) arglist 参数是赋给包含在 Variant 中的数组元素的值的列表(用逗号分隔)。如果没有指定此参数,则
Abs 函数 返回数字的绝对值。 Abs(number) number 参数可以是任意有效的数值表达式。如果 number 包含 Null,则返回 Null;如果是未初始化变量,则返回 0。
FormatPercent 函数 返回表达式,此表达式已被格式化为尾随有 % 符号的百分比(乘以 100 )。 FormatPercent(expression[,NumDigitsAfterD
FormatNumber 函数 返回表达式,此表达式已被格式化为数值。 FormatNumber( expression [,NumDigitsAfterDecimal [,Inc
我是一名优秀的程序员,十分优秀!