2016-06-13 77 views
0

在此site,他们给文字类的这个例子:C++ - amperand +括号数组的语法?

#include <iostream> 
#include <stdexcept> 

class conststr 
{ 
    const char* p; 
    std::size_t sz; 
public: 
    template<std::size_t N> 
    constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {} 

    constexpr char operator[](std::size_t n) const 
    { 
     return n < sz ? p[n] : throw std::out_of_range(""); 
    } 
    constexpr std::size_t size() const { return sz; } 
}; 

constexpr std::size_t countlower(conststr s, std::size_t n = 0, 
              std::size_t c = 0) 
{ 
    return n == s.size() ? c : 
      s[n] >= 'a' && s[n] <= 'z' ? countlower(s, n + 1, c + 1) : 
             countlower(s, n + 1, c); 
} 

// output function that requires a compile-time constant, for testing 
template<int n> 
struct constN 
{ 
    constN() { std::cout << n << '\n'; } 
}; 

int main() 
{ 
    std::cout << "the number of lowercase letters in \"Hello, world!\" is "; 
    constN<countlower("Hello, world!")>(); // implicitly converted to conststr 
} 

程序导致输出

the number of lowercase letters in "Hello, world!" is 9 

但我不明白这个程序的一个组成部分。也就是说,这条线的位置:

constexpr conststr(const char(&a)[N]) : p(a), sz(N - 1) {} 

const char(&a)[N],这是什么语法究竟是什么意思?它有名字吗?

回答

1

代码const char(&a)[N]需要括号说“a是的Nconst char秒的数组的引用

如果没有括号,你必须const char &a[N] - 这将是” aNconst char引用数组”,这是不允许的

这就是为什么我喜欢typedef S,使这些各种各样的事情更清楚:

typedef const char ArrayN[N]; 

ArrayN &a;