dajee
dajee

Reputation: 964

Static variable inside a static function?

Simple C++ Simulation of Java String Literal Pool

Hi,

I can't make a call from a private static variable in my MyString class. Any idea?

static void displayPool() {
    MyString::table->displayAllStrings();
}
StringTable* (MyString::table) = new StringTable();

both of those are declared in MyString class. table is a private variable.

Thanks.

EDIT: headerfile

#ifndef MYSTRING_H
#define MYSTRING_H

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
#define POOLSIZE 100

class StringTable {
 public:
    StringTable();
    int addString(const char *str);
    char* getString(int i);
    void deleteString(int i);
    void displayAllStrings();
    void addCount(int);
    void minusCount(int);
 private:
    char** array; //da pool
    int* count;
    int size;
    int numStrings;
};

class MyString {
 public:
   MyString(const char*);
   MyString(const MyString&);
   ~MyString();
   static void displayPool();
   MyString& operator=(const MyString &);
   char* intern() const;
 private:
   int length;
   int index;
   static StringTable* table;
   friend MyString operator+(const MyString& lhs, const MyString& rhs);
   friend ostream& operator<<(ostream & os, const MyString & str);
 }; 

#endif

Upvotes: 2

Views: 2398

Answers (4)

David Hammen
David Hammen

Reputation: 33136

static void displayPool() {
    MyString::table->displayAllStrings();
}

This is not doing what you think it is doing. It is defining the free function displayPool. All that the keyword static does is to keep the function local to the source file in which the function is defined. What you want is to define the static member function MyString::displayPool():

void MyString::displayPool() {
    table->displayAllStrings();
}

The MyString:: before displayPool is essential. You do not want the static keyword here; adding that would be an error. Finally, note that there is no need for the MyString:: to qualify table. A static member function can see all of the static data members without a need for qualification. The only reason you would need to qualify table is if there was a global variable named table; then table would be ambiguous.

Upvotes: 6

CrazyCasta
CrazyCasta

Reputation: 28362

What you want in this case is the following:

void MyString::displayPool() {
    MyString::table->displayAllStrings();
}

Upvotes: 1

Leon
Leon

Reputation: 1141

have you declared

StringTable* table;

in the class definition of MyString with the public access specifier?

Upvotes: 0

CrazyCasta
CrazyCasta

Reputation: 28362

If you want a static variable inside your static function you should just do:

static void displayPool() {
    static StringTable* table = new StringTable();

    table->displayAllStrings();
}

However I have a feeling the problem might be asking you to create a static method for some class. You might want to re-read the problem.

Upvotes: 0

Related Questions