gpt4 book ai didi

C++构造函数语法解释

转载 作者:行者123 更新时间:2023-11-30 03:08:20 25 4
gpt4 key购买 nike

我正在浏览 a tutorial for building an AST with the help of Clang/LLVM .

我在那里看到了这个语法:

struct PPContext {
// Takes ownership of client.
PPContext(clang::DiagnosticClient* client = 0,
const std::string& triple = LLVM_HOSTTRIPLE)
: diagClient(client == 0?new clang::TextDiagnosticPrinter:client),
diags(diagClient),
target(clang::TargetInfo::CreateTargetInfo(triple)),
headers(fm),
pp(diags, opts, *target, sm, headers)
{
// Configure warnings to be similar to what command-line `clang` outputs
// (see tut03).
// XXX: move warning initialization to libDriver
using namespace clang;
diags.setDiagnosticMapping(diag::kind,diag::MAP_IGNORE);
//diag::warn_pp_undef_identifier was the initial value instead of diag::kind. But I changed since it gave error.
}

~PPContext()
{
delete diagClient;
delete target;
}

clang::DiagnosticClient* diagClient;
clang::Diagnostic diags;
clang::LangOptions opts;
clang::TargetInfo* target;
clang::SourceManager sm;
clang::FileManager fm;
clang::HeaderSearch headers;
clang::Preprocessor pp;
};

和:

//What is the constructor doing here ? The construct looks very different and difficult to comprehend !!!
// Could someone break it up for me ?
PPContext(clang::DiagnosticClient* client = 0,
const std::string& triple = LLVM_HOSTTRIPLE)
: diagClient(client == 0?new clang::TextDiagnosticPrinter:client),
diags(diagClient),
target(clang::TargetInfo::CreateTargetInfo(triple)),
headers(fm),
pp(diags, opts, *target, sm, headers)
{
// Configure warnings to be similar to what command-line `clang` outputs
// (see tut03).
// XXX: move warning initialization to libDriver
using namespace clang;
diags.setDiagnosticMapping(diag::kind,diag::MAP_IGNORE);
//diag::warn_pp_undef_identifier was the initial value instead of diag::kind. But I changed since it gave error.
}

请让我知道是否有任何其他 Material 可以很好地帮助和学习经验。谢谢

最佳答案

这些是构造函数初始值设定项。他们用给定的值初始化类成员。例如:

class TestClass
{
private:
int someField;

public:
TestClass() : someField(5) { }
};

将在调用 TestClass() 构造函数期间将成员 someField 初始化为值为 5。您可以使用 , 分隔多个初始化器以初始化多个成员。您还可以将参数从构造函数传递给这些初始化器,例如:

class TestClass
{
private:
int someField;

public:
TestClass(int _someField) : someField(_someField) { }
};

调用此构造函数时,传递给 _someField 的值将用于初始化 someField。

还要考虑继承。使用第二个 TestClass 作为我们的基础,我们得到以下派生类型:

class TestClassDerived : public TestClass
{
public:
TestClassDerived(int _someField) : TestClass(_someField) { }
};

这就是您可以从派生类型构造基类并将参数传递给非默认构造函数的方式。否则,您将无法使用非默认构造函数使用适当的参数构造基础。

关于C++构造函数语法解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5122831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com