[英]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 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.