2013-04-21 79 views
1

我想要定义一些运营商。运营商的定义

我这样做是根据本文档:

http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html

是否有应定义两次操作?

我认为这是索引运算符。我对吗?我定义它如:

int operator [] (const int power) const{ 
    // here there is some code 
} 

假设我正确地实现它,应该有两次定义的运算符是什么?

它支持接下来的事情吗?

a[1] = 3; 
cout << a[1]; // I defined the << operator 

任何帮助赞赏!

+0

第二个将工作,但所述第一会失败An的方法的例子,因为不必返回一个参考。 – 0x499602D2 2013-04-21 15:24:39

+0

所以我必须定义它:int&operator [](const int power)const; – 2013-04-21 15:27:31

+1

是的,你应该定义返回'int&'的运算符的另一个重载。 – 0x499602D2 2013-04-21 15:28:40

回答

2

我认为这是索引运算符。我对吗?

差不多。它被称为下标运算符,它必须接受一个单个参数。您的运营商接受两个,这使您的代码非法。

它支持接下来的事情吗?

假如你有一个正确编写operator [](不从应用程序的逻辑知道一些背景,我不能告诉你怎么写一个),那么无论是你提到要支持的指令。

然而,为了这个:

a[1] = 3; 

是合法的(如果返回一个基本类型),operator []应该返回一个左参考 - 因此,int&而不是int。当然,这意味着左值引用所绑定的对象不能是本地对象或临时对象,因为这意味着返回一个参考。

int& operator [] (const int power) { // <== The function cannot be "const" if you 
//^        //  are returning a non-const lvalue ref 
            //  to a data member or element of a data 
            //  member array 
    // here there is some code 
} 

您可能还需要一个const版本下标操作的:

int operator [] (const int power) const { 
// No need to use a int const& ^^^^^ 
// here, that is basically the This member function can be const, since it is 
// same as returning an int by neither modifying the object on which it is 
// value       invoked, nor returns any non-const lvalue ref 
            to a data member or an element of data member 
    // here there is some code 
} 
2

您可能需要同时具有const和非const版本的运营商:

int operator[](int index) const { ... } 
int& operator[](int index) { ... } 

这将允许您的示例中给出的两种用法。即使aconst,它也将允许第二次使用。

+0

他们也这么做? – 2013-04-21 15:29:55

+1

@AlonShmiel:他们不这样做。第一个返回一个int值,它大概是从该对象内的对象中的值复制的,但该副本没有持续连接到容器。第二种方法通常授予调用代码读/写访问被视为在该对象内的int值的权限 - 调用代码可以写入这个'x [i] = n;'并且变化影响对象中的数据本身。第二个仅在对象不是const时调用,以防止修改const对象。 – 2013-04-21 15:37:53

1

为了支持分配有两个选项

  1. 的索引操作符[]返回引用
  2. 的索引操作符[]返回实现分配

第一种情况是最简单的一个代理对象,但不允许您区分读取和写入操作。第二种方法是有点复杂,但允许更多的控制:

(2)在下面的

struct MyArray { 
    std::vector<int> v; 

    MyArray(int n) : v(n) {} 

    struct ItemRef { 
     MyArray& a; 
     int index; 

     ItemRef(MyArray& a, int index) 
      : a(a), index(index) 
     {} 

     int operator=(int x) { 
      printf("Writing to element %i\n", index); 
      a.v[index] = x; 
      return x; 
     } 

     operator int() { 
      printf("Reading element %i\n", index); 
      return a.v[index]; 
     } 
    }; 

    ItemRef operator[](int index) { 
     if (index < 0 || index >= int(v.size())) 
      throw std::runtime_error("Invalid index"); 
     return ItemRef(*this, index); 
    }; 
};