繁体   English   中英

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

[英]Why is it an error to construct an unassigned temporary instance of a class with a const char* variable when that class has a const char* constructor?

为什么使用此代码(由const char *变量构造的未分配临时变量):

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

int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A(constCharPointerVariable);
    return 0;
}

给这些错误?

error C2512: 'A' : no appropriate default constructor available
error C2040: 'constCharPointerVariable' : 'A' differs in levels of indirection from 'const char *'

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

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

int main()
{
    const char* constCharPointerVariable = "StringLiteral";
    A a(constCharPointerVariable);
    return 0;
}

没有错误。

以及以下代码(从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;
}

没有错误。

如果可以在C ++规范中提供部分编号以指定不允许的第一个代码示例,则可以加分。

A(constCharPointerVariable);

这实际上是A名为constCharPointerVariable的类型A变量的声明。 它不会创建临时对象。

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

error: redefinition of 'constCharPointerVariable' with a different type
    A(constCharPointerVariable);
      ^

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

int x(0);
int (x);

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

相关作品包括:

  • 声明 -> ptr-declarator
  • ptr声明器 -> noptr声明器 | 声明者编号
  • noptr-declarator -> ( ptr-declarator )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM