我看过一个非常相似的问题,但我不太确定我理解答案。如果我委托构造函数,会发生初始化列表中的哪些初始化?
例子:
MyClass::MyClass(int a, int b)
:
MyClass(a, b, NULL),
int1(a),
int2(b),
pOtherClass(NULL)
{
}
MyClass::MyClass(int a, int b, Other *p)
:
int1(a),
int2(b),
pOtherClass(p)
{
if (pOtherClass == NULL)
{
pOtherClass = &DefaultInstance;
}
}
Run Code Online (Sandbox Code Playgroud)
由于编译器设置,我必须拥有两个类的完整初始值设定项列表。但我不想要的是:
int, int) 调用第二个构造函数( int, int, Other *)pOtherClasspOtherClass给NULL.我在顶部链接的问题似乎表明这种行为不会发生,但是 ( ) 构造函数中的初始化列表有什么意义呢int, int?只是为了让编译器高兴吗?
我有一个有两个构造函数的类.
class Foo {
Foo(B b) {... }
Foo(int n) : Foo(buildBFromInt(n)) {} ??
}
Run Code Online (Sandbox Code Playgroud)
第一个需要一些对象,我想要第二个首先从更简单的类型创建对象.这可能吗 ?
我最近意识到在C++ 11中我们可以调用委托初始化列表构造函数
Foo() : Foo{42} // delegate to Foo(initializer_list<>)
Run Code Online (Sandbox Code Playgroud)
这种语法是否正确?它似乎是,虽然我希望在调用函数时总是使用括号,比如Foo({42}).下面的示例代码在clang ++和g ++ 中编译都很好
#include <iostream>
#include <initializer_list>
struct Foo
{
Foo() : Foo{42} // I would have expected invalid syntax, use Foo({42})
{
std::cout << "Foo()... delegating constructor\n";
}
Foo(std::initializer_list<int>)
{
std::cout << "Foo(initializer_list)\n";
}
};
int main()
{
Foo foo;
}
Run Code Online (Sandbox Code Playgroud)
我很清楚统一初始化,比如使用声明对象{ },但不知道我们也可以调用构造函数.我们不能调用函数,以下不编译:
#include <initializer_list>
void f(std::initializer_list<int>){}
int main()
{
f{5}; // compile time error, must use f({5})
} …Run Code Online (Sandbox Code Playgroud) c++ constructor initializer-list c++11 delegating-constructor
以下代码不会将结构字符串成员初始化为相同的值。
#include <string>
#include <iostream>
struct S
{
std::string s1;
std::string s2;
S(std::string const& s) : s1{s}{}
S(int i) : S([&]{
s2 = std::to_string(i);
return std::to_string(i);
}())
{}
};
int main()
{
S s{123};
std::cout << s.s1 << "|" << s.s2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我在gcc(尝试了不同的版本)和123|clang(也有不同的版本)中通过Wandbox 遇到了分段错误。
我收到读取访问冲突Visual Studio 15.9.16
谢谢。
我了解在C ++ 11中,构造函数委托可以如下所示:
class Foo
{
public:
Foo()
{
// Some code to be ran first
}
Foo(std::string bar): Foo() // Runs the code to be ran first
{
// Some code to be ran second, presumably using bar
}
};
Run Code Online (Sandbox Code Playgroud)
我想知道如何以某种方式扭转这种局面。也就是说,在Foo()调用构造函数的情况下,我想运行一些代码来找出a的值,std::string然后将其用于Foo(std::string bar)完成初始化。因此,Foo()它同时运行自己的代码和中的代码Foo(std::string bar),而后者仅运行自己的代码,例如
class Foo
{
public:
Foo()
{
std::string bar_figured_out;
// Figures out the value for bar_figured_out
Foo(bar_figured_out); // I know this wouldn't work, just an example of …Run Code Online (Sandbox Code Playgroud)