[英]private and public operator overloading
我試圖實現Horner的方法並面臨一個問題:
root@host:~# cat | g++ -x c++ -std=gnu++11 - && ./a.out
#include <iostream>
#include <iomanip>
#include <iterator>
#include <vector>
#include <numeric>
#include <algorithm>
#include <random>
#include <chrono>
#include <cstdlib>
template< typename F >
class horner
{
public :
typedef std::vector< F > V;
horner(F const & x_, V const & c_)
: x(x_)
, c(c_)
, y(0.0L)
{ ; }
operator F const () const
{
return std::accumulate(c.rbegin(), c.rend(), *this).y;
}
private :
friend horner std::accumulate< typename V::const_reverse_iterator, horner >(typename V::const_reverse_iterator, typename V::const_reverse_iterator, horner);
void operator = (F const & rhs)
{
y = rhs;
}
operator F ()
{
y *= x;
return y;
}
F const & x;
V const & c;
F y;
};
#define N_COEFF_PARABOLA 3
int main()
{
typedef double F;
typedef typename horner< F >::V V;
V c;
unsigned seed(std::chrono::system_clock::now().time_since_epoch().count());
std::cout << "seed = 0x"
<< std::uppercase << std::hex << std::setfill('0') << std::setw(sizeof(seed) * 2)
<< seed << std::endl;
std::mt19937 generator(seed);
std::generate_n(std::back_inserter(c), N_COEFF_PARABOLA, generator);
std::cout << "coefficients: ";
std::copy(c.begin(), c.end(), std::ostream_iterator< F >(std::cout, " "));
std::cout << ';' << std::endl;
F const x(generator());
F const y(horner< F >(x, c));
std::cout << "y(" << x << ") = " << y << std::endl;
// naive
F xx(1.0L);
F yy(0.0L);
for (typename V::size_type i(0); i < c.size(); ++i) {
yy += c[i] * xx;
xx *= x;
}
std::cout << "y'(" << x << ") = " << yy << std::endl;
return EXIT_SUCCESS;
}
// press ^D
<stdin>: In function ‘int main()’:
<stdin>:39:5: error: ‘horner<F>::operator F() [with F = double]’ is private
<stdin>:71:32: error: within this context
root@host:~#
在我看來,問題不應該出現,因為main()
只看到類型轉換運算符的運算operator F const & () const
版本。 但它是。
錯誤的原因是什么?
可見性和可訪問性的概念在C ++中是完全正交的。 如果方法可見但不可訪問,則編譯器可能會在重載決策中選擇它並產生硬錯誤,因為它無法使用它。 這是有目的地完成的,因此代碼在獲取或失去訪問權限時不會以靜默方式更改語義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.