【问题标题】:Unclear C++ syntax in operator overloading运算符重载中的 C++ 语法不明确
【发布时间】:2014-12-23 22:17:47
【问题描述】:

我还是 C++ 新手,并试图理解表达式模板。我在Wikipedia 上遇到了一个示例代码。我了解了大部分程序及其工作原理,但我不清楚编译器如何解释这些行:

 operator A&()             { return static_cast<      A&>(*this); }
 operator A const&() const { return static_cast<const A&>(*this); }

来自下面的基本表达式模板类。 通常,运算符重载的语法是return_datatype operator+ (args){body}(例如 + 运算符),但这会产生错误,并且函数中的那些会编译而没有任何错误。任何人都可以解释这两行吗?运算符之前的A&amp;A const&amp; 是做什么的?为什么A&amp; operator() (){}A const&amp; operator() (){} 不起作用?它给出了错误:

no matching function for call to 'Vec::Vec(const Expr<Vec>&)'
   ExprSum(const Expr<A>& a, const Expr<B>& b): _u(a), _v(b) {}

-普拉纳夫

完整代码:

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;


template <class A>
class Expr{
public:
  typedef std::vector<double>         container_type;
  typedef typename container_type::size_type   size_type;
  typedef typename container_type::value_type  value_type;
  typedef typename container_type::reference   reference;

  size_type size() const  {return static_cast<A const&>(*this).size(); }
  value_type operator [] (size_t i) const {return static_cast<A const&> (*this)[i];}
  operator A&()             { return static_cast<      A&>(*this); }
  operator A const&() const { return static_cast<const A&>(*this); }
};


class Vec : public Expr<Vec> {
private:
  container_type x;
public:
  Vec(){}
  Vec(size_type length) :x(length) {}
  size_type  size() const { return x.size(); }

  reference operator [] (size_type i){
    assert(i < x.size());
    return x[i];
  }
  value_type operator [] (size_type i) const {
    assert(i < x.size());
    return x[i];
  }

  template <class A>
  void operator = (const Expr<A>& ea){
    x.resize(ea.size());
    for(size_t i = 0; i < x.size(); i++){
      x[i] = ea[i];
    }
  }

};


template <class A, class B>
class ExprSum : public Expr <ExprSum <A,B> >{
private:
  A _u;
  B _v;
public:
  typedef Vec::size_type size_type;
  typedef Vec::value_type value_type;

  ExprSum(const Expr<A>& a, const Expr<B>& b): _u(a), _v(b) {}
  value_type operator [] (size_t i) const { return (_u[i] + _v[i]); }
  size_type size() const { return _u.size(); }
};


template <class A, class B>
ExprSum <A,B> const operator + (Expr<A> const& u, Expr<B> const& v){
  return ExprSum <A,B> (u,v);
}



int main(){

  size_t n = 10;
  Vec x(n);
  Vec y(n);
  Vec z;

  for(size_t i = 0; i < n; i++){
    x[i] = i;
    y[i] = 2*i;
  }

  z = x + y;

  cout << z[7] << endl;

  cout << "Hello world!" << endl;
  return 0;
}

【问题讨论】:

  • 这些称为转换运算符或强制转换运算符。它们用于为不同类型之间的转换提供语义。见here
  • 不要说“不起作用”,而是说明您遇到了什么问题

标签: c++ templates operator-overloading


【解决方案1】:

这是conversion operator。它看起来类似于普通的重载运算符,但它没有指定的返回类型,并且在运算符符号的位置上,您有转换目标类型。

【讨论】:

  • 感谢@Sebastian 指出它是一个转换运算符。提供的链接确实澄清了我的疑问。谢谢-Pranav
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
相关资源
最近更新 更多