简体   繁体   中英

“Reset” object to default values; recall constructor?

I have a class characterData with a constructor:

class characterData() {
    private:
        int position[2];
        vector<vector<int> > pixelData;
        int num;
    public:
        characterData() {
            num = -1;
        }
        void setValues(int p[2], vector<vector<int> > v, int n) {
            position[0] = p[0];
            position[1] = p[1];
            pixelData = v;
            num = n; // if setValues() is called, n will always > -1
        }
};

I do it this way so I can have an "empty" characterData in my code. My thought process is if num == -1 , setValues() has not been called on the characterData object.

Later in my code I have a characterData k which is only initialized, setValues() has not been called upon it, so k.num == -1 .

Eventually I change the value of k but wish to "reset" it to its original form.

characterData k;
// some assignments happen, k = something else
k = new characterData(); // reset k

The above doesn't work. I need to reset k such that k.num == -1 . There is no member setter/mutator function that can allow me to change num at all: my thought was to recall constructor but this doesn't work.

How do I reset k to an "empty" state?

Just use the default constructor again:

  characterData c;
  c.setvalues( ... );
  c = characterData();

Although I wouldn't say this is a particularly great design.

Add a clear function maybe?

    void clear() {
        num = -1;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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