-3

Hey guys how can I achieve changing this piece of code to use classes instead of a struct. I briefly understand how classes work but im completely confused how to change this piece of code thanks. The code it's self is to scan a .txt file and then search the .txt file to select a word then print the results.

The basic layout would consist of

class Word {
public:
      string word;
      string definition;
      int usageFrequency;
private:
Bart
  • 19,692
  • 7
  • 68
  • 77
subzerok
  • 5
  • 2

2 Answers2

3

In C++, struct and class are identical except for the default access allowed - class is private while struct is public. There's no need to convert, what you have is just fine.

As a matter of convention usually struct is reserved for structures that don't have any methods. However I've found that adding a constructor or operator< and operator== is perfectly acceptable and is very convenient.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
2

The difference between struct and class is that struct members are public by default and in class they are private by default. Here is a struct Word converted to class, the only modification you need:

class Word {
public:
    string word;         
    string definition;   
    int usageFrequency;  

    //Constructor
    Word(const string &theWord, const string &theDefinition)
    {
        word = theWord;
        definition = theDefinition;
        usageFrequency = 0;
    }
};
cpp
  • 3,743
  • 3
  • 24
  • 38