c++ - *this-> 不能作为函数使用

标签 c++ operator-overloading this

这是我在头文件中创建的类的摘录:

typedef double real;

class Grid{
   public :

      explicit Grid ();
      explicit Grid(size_t level );
      Grid(const Grid & grid );

      ~ Grid ();


      const Grid & operator =( const Grid & grid );

      inline real & operator ()( size_t i , size_t j );
      inline real operator ()( size_t i ,size_t j ) const;

      void fill( real value );
      void setBoundary ( real value );

 private :

   size_t y_ ; // number of rows 
   size_t x_ ; // number of columns 
   real h_ ; // mesh size 
   real * v_ ; //  values 
};

这是我为之前在单独的 .cpp 文件中声明的函数编写的代码的摘录。请注意,我只包含了与我的错误相关的部分。

  inline real&  Grid :: operator ()( size_t i , size_t j ){
    if( (i >= y_) || (j>=x_ ) )
      throw std::invalid_argument( "Index out of bounds" );
    return v_ [i* x_ +j];
  }

  inline real Grid::operator ()( size_t i ,size_t j ) const{
    if( (i >= y_) || (j>=x_ ) )
      throw std::invalid_argument( "Index out of bounds" );
    return v_[i* x_+j];
  }


  void Grid::fill( real value ){
   for(size_t i=1;i<y_;++i){
    for(size_t j=1;j<x_;++j)
     v_(i,j)=value;
   }

  }

 void Grid::setBoundary ( real value ){
    size_t i = 0;
    for(size_t j=0;j<x_;++j){
     v_(i,j)=value;
    }
    i = y_;
    for(size_t j=0;j<x_;++j){
     v_(i,j)=value;
    }
    size_t j = 0;
    for(size_t i=0;i<y_;++i){
     v_(i,j)=value;
    }
    j = x_;
    for(size_t i=0;i<y_;++i){
     v_(i,j)=value;
    }
  }

我遇到了一个错误

((Grid*)this)->Grid::v_ cannot be used as a function

每当我尝试在 fillsetBoundary 函数中使用重载的 () 运算符时。我曾尝试在网上寻找类似的错误,但遗憾的是没有取得太大进展。你有什么建议吗,因为我认为重载运算符的实现是正确的,而且据我所知我还没有命名任何与成员变量同名的函数。

最佳答案

v_ 是一个real*,即一个指针。指针没有 operator(),因此您不能编写 v_(something)

您已经为您的 Grid 类提供了 operator() 的重载。如果要使用该重载,则需要在 Grind 类的对象上使用 ()v_ 不是您的 Grid 类的对象。

您可能想在当前对象上调用 operator()(即正在调用 fillsetBoundary 的对象)。为此,您需要编写 (*this)(arguments)

关于c++ - *this-> 不能作为函数使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16374801/

相关文章:

javascript - 如何在 forEach 循环内使用 'this' 进行函数调用

javascript - 在 JQuery 方法中设置匿名函数的 'this' 上下文

c++ - 如何使用 LD_LIBRARY_PATH 和链接使其真正正确?

c++ - 模板类的标准流输出

java - BigInteger 和 BigDecimal 的平方根和++ 运算符

C# GetHashCode/Equals 覆盖未调用

c++ - "this"指针上的 const_cast 是未定义的行为吗?

c++ - 涉及模板化转换运算符和隐式复制构造函数的歧义

c++ - C++中如何设置文件编码格式为UTF8

c++ - 可变数量的构造函数参数取决于整数模板