为什么用const char*变量构造类的未分配临时实例是错误的,而该类具有const char*constructor
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 *'
而这段代码(由常量字符*变量构造的临时变量):
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);
这实际上是一个名为constCharPointerVariable
的A
类型变量的声明。它不会创建临时对象。
如果你使用clang,你会得到更有用的错误消息:
error: redefinition of 'constCharPointerVariable' with a different type
A(constCharPointerVariable);
^
作为一个更简单的示例,以下内容是无效的,因为它声明了同一范围中的两个int
对象,均命名为x
:
int x(0);
int (x);
至于为什么以这种方式解析代码,您可以在中找到Declarator的语法规则C++11的§A.7。基本上,当您声明一个变量时,您可以将其名称括在任意数量的括号中。
相关产品包括:
- 声明符->ptr声明符
- ptr声明符->noptr声明器|声明符id
- noptr声明符->
(
ptr声明器)
相关文章:
- 在字符串函数中抛出'char const*'实例后调用的终止
- 双重标准?为什么只有 char* const&a = "bla" 的警告?
- 包括"lvtocon.h",未定义对'operator<<(std::ostream&, char const*)的引用
- 为什么 const char* const & = 可以编译"hello"?
- 将字符串文本常量定义为 char const* 和 wchar const*
- 如何将std::wstring转换为char const[]
- "char const * name() const _WEBSOCKETPP_NOEXCEPT_TOKEN_ {"剂量是什么意思
- 使用提升对字符串进行标记化时,将令牌转换为 char* const* 时失败
- 如何从 std::initializer_list<char const* 构建 std::vector<std::string>>
- 将 std::vector<std::string> 转换为 const char* const*
- 引发"char const*"错误的实例后调用的终止
- 将const char * const参数成员分配给新值
- 从'const char**'到'char* const*'的转换无效
- 从 sub_match<常量字符 *>' 转换为'const char *const &'
- char*const和constchar*之间有什么区别?(重复-需要更多澄清)
- 使用工厂方法时编译器错误:无法转换"const std::p air<char* const
- HEVC 解码器端口 Android 警告:从 'signed char*' 到 'char const* 的转换无效*
- 如何从'char const*'中删除常量
- 'char const *str'作为模板参数
- 为什么不;t strlen(.)应为const char*const str,而不是const char*