c++ - 私有(private)和公共(public)运算符重载

标签 c++ operator-overloading

我尝试实现霍纳的方法,遇到了一个问题:

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++ 中是完全正交的。如果一个方法可见但不可访问,编译器可能会在重载决议中选择它并产生一个硬错误,因为它不能使用它。这是有意为之的,因此代码在获得或失去访问权限时不会悄悄地更改语义。

关于c++ - 私有(private)和公共(public)运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13174035/

相关文章:

c++ - 重载在参数中获取指针的运算符

c# - 定义运算符 + 、 = 和 +=

c++ - 为什么 constexpr 与模板一起工作?

c++ - 为什么按此顺序评估 '--++a-​-++ +b--'?

c# - C# 中泛型类的算术运算符重载

c++ - 通过成员函数保持来自 fstream 的流打开

c++ - 键盘有一些问题

c++ - std::cout 给出与 qDebug 不同的输出

c++ - 错误:undefined reference to. .. 在另一个成员函数中调用成员函数时

c++ - 可以使用 type_traits/SFINAE 来查找类是否定义了成员 TYPE?