简体   繁体   English

如何在 c++ 中超载 class 访问器

[英]How to overload class accessor in c++

I have a class that just has one single int value, and 2 more classes that extend this class.我有一个 class,它只有一个 int 值,还有 2 个扩展这个 class 的类。 I want to be able to access this int value by just calling an instance of the class, rather than instance.val, for simplicity.为了简单起见,我希望能够通过调用 class 的实例而不是 instance.val 来访问这个 int 值。

class thing {
  public:
    int val;
    thing(int a) : val(a) {}
};

class proc: public thing {
  public:
    proc (int a) : thing(a){}
};

class res : public thing {
  public:
    res(int a) : thing(a){}
};

int main(){
  proc x (3);
  res y (5);
  int* array = new int[10];

  //I want to be able to do this:
  cout << x << " " << y << endl;
  array[x]; array[y];

  //rather than this:
  cout << x.val << " " << y.val << endl;
  array[x.val]; array[y.val];
}

Basically, i want to use my created classes as ints, since all i need to store is the int value, but i need 2 different types of ints, as they will represent 2 slightly different, but almost the same things.基本上,我想将我创建的类用作整数,因为我需要存储的只是整数值,但我需要 2 种不同类型的整数,因为它们将代表 2 种略有不同但几乎相同的东西。

Add a conversion operator to your class:将转换运算符添加到 class:

class thing {
    public:
        int val;
        thing(int a) : val(a) {}

        operator int() const { return val; }
};

Now, you can pass an instance of your class anywhere an int is accepted.现在,您可以在任何接受int的地方传递 class 的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM