开发者

operator function in C++ and compile error relating to it

开发者 https://www.devze.com 2023-04-12 01:27 出处:网络
there are probably several ways I will expose my ignorance with this question :) First, I think this is C++ code, but the extension of the file is .C (so maybe it is C?)

there are probably several ways I will expose my ignorance with this question :)

First, I think this is C++ code, but the extension of the file is .C (so maybe it is C?)

Anyway, I am trying to compile a program called Sundance (Sentence UNDerstanding ANd Concept Extraction) which is a Natural Language Processing tool. The compile error I get relates to the following:

// This class is used internally to keep track of constituents that are
//开发者_高级运维 potential subjects for clauses during clause handling.
class PotentialXP {
public:
  Constituent* XPPtr;
  unsigned int Distance;
  unsigned int ClauseIndex;
  unsigned int ConstIndex;

  PotentialXP() {
    XPPtr         = 0;
    Distance      = 0;
    ClauseIndex   = 0;
    ConstIndex    = 0;
  };

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

  void Set(Constituent* w,
           unsigned int x,
           unsigned int y,
       unsigned int z){
    XPPtr         = w;
    Distance      = x;
    ClauseIndex   = y;
    ConstIndex    = z;
  };
};

The error is "cast from ‘Constituent* const*’ to ‘int’ loses precision"

and relates to the lines:

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

I understand why I get an error. XPPtr is of type Constituent*, so how can it be converted to an integer? Can anyone figure out what the author of the code wants to do here, and how I might rewrite this line so it compliles? What is an operator function (if that's what you call it) for?

Any advice much appreciated!


That compiles fine for me. You are on a 64-bit machine, where size_t is larger than int.

Explanation: you can historically convert a pointer an int

struct Foo {};

int main ()
{
    Foo * f = new Foo ();
    std :: cout << (int)f; // Prints 43252435 or whatever
}

If you want an integer which is the same size as a pointer, use size_t or ssize_t.

And why on earth are you writing operator int() like that anyway? Do you want operator bool() to test for validity? In which case a function body of return NULL != XPPtr would be better style -- clearer, at least.


The line operator int() const states a how your object can be cast to int.

The Constituent* can be cast to int because both types are usually the same size. I do not think that this is what the programmer intended, since the raw pointer value is of no semantic use. Maybe there should be a field lookup? E.g:

operator int() const {
  return (int)XPPtr->somevalue;    
};
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号