当该类具有const char*构造函数时,为什么使用const char*变量构造类的未分配临时实例是错误的?

Nei*_*ice 1 c++ constructor compiler-errors

为什么这段代码(从const char*变量构造的未分配的临时变量):

class A
{
public:
    A(const char*) {}
};

int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A(constCharPointerVariable);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

给出这些错误?

error C2512: 'A' : no appropriate default constructor available
error C2040: 'constCharPointerVariable' : 'A' differs in levels of indirection from 'const char *'
Run Code Online (Sandbox Code Playgroud)

而这段代码(分配的临时变量是从const char*变量构造的):

class A
{
public:
    A(const char*) {}
};

int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A a(constCharPointerVariable);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

没有错误.

这段代码(从const char*变量static_cast到const char*构造的未分配的临时变量):

class A
{
public:
    A(const char*) {}
};

int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A(static_cast<const char*>(constCharPointerVariable));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

没有错误.

如果您可以在C++规范中提供指定第一个不允许的代码示例的节号,则可以使用加分点.

Jam*_*lis 7

A(constCharPointerVariable);
Run Code Online (Sandbox Code Playgroud)

这实际上是一个A名为variable的变量的声明constCharPointerVariable.它不会创建临时对象.

如果您使用了clang,则会收到更有用的错误消息:

error: redefinition of 'constCharPointerVariable' with a different type
    A(constCharPointerVariable);
      ^
Run Code Online (Sandbox Code Playgroud)

作为一个更简单的示例,以下内容无效,因为它int在同一范围内声明了两个对象,两个对象都命名为x:

int x(0);
int (x);
Run Code Online (Sandbox Code Playgroud)

至于为什么以这种方式解析代码,你可以在C++ 11的§A.7中找到声明符的语法规则.基本上,当您声明变量时,可以将其名称括在任意数量的括号中.

相关作品包括:

  • 声明者 - > ptr声明者
  • ptr-declarator - > noptr-declarator | 声明符-ID
  • noptr-declarator - > ( ptr-declarator )