[英]How to use a cv-qualifier for a method that returns a reference to an array?
如果我有一個成員函數返回對數組的引用( https://stackoverflow.com/a/5399014/4304120 ),如何在函數中添加const限定符? 此代碼不在Visual C ++ 2010下編譯。
struct A
{
int data[10];
// this compiles
const int (&f1())[10]
{
return data;
}
// error C2143: syntax error : missing ';' before '<cv-qualifer>'
const int (&f2())[10] const
{
return data;
}
};
我提出的一些解決方案在我看來比這個問題的直接答案更具可讀性。 我確定那里有C語法愛好者,我向他們道歉,因為我有可怕的記憶,而且我無法記住那些C規則。
您可以通過使用類型別名來避免奇怪的基於C的語法:
struct A {
using data_type = int[10];
data_type data;
data_type& f1() { return data; }
data_type const& f2() const { return data; }
};
或者使用typedef
(對於C ++ 11之前):
struct A {
typedef int data_type[10];
data_type data;
data_type& f1() { return data; }
data_type const& f2() const { return data; }
};
從C ++ 14開始,您還可以使用auto
返回類型:
struct A {
int data[10];
auto& f1() { return data; }
auto const& f2() const { return data; }
};
從C ++ 11開始,您也可以使用std::array
:
struct A {
using data_type = std::array<int, 10>;
data_type data;
data_type& f1() { return data; }
data_type const& f2() const { return data; }
};
並簡化為:
struct A {
std::array<int, 10> data;
};
這在功能上有些等同,但在眼睛上更容易。
const int (&f2() const )[10]
{
return data;
}
使用typedef。 它會讓每個人的生活更輕松:
struct A
{
using Data = int[10];
Data data;
Data const& f1()
{
return data;
}
Data const& f2() const
{
return data;
}
};
使用std::array<int, 10>
可以實現同樣的目的:
std::array<int, 10> data;
std::array<int, 10> const& f2() const { return data; }
這是std::array
優於原始數組的另一個優點。
那么typedef可以解決你的問題,並使它更具可讀性:
struct A
{
typedef int array_t[10];
...
const array_t& f2() const
{
return data;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.