Avgar
Avgar

Reputation: 21

Illegal call of non-static member function

I wish to make a calculator that can calculate numbers of almost any length.

The first function that I needed is one that converts a string into a linked list and then returns a pointer to the head of the list.

However, when compiling I am faced with an error: error C2352: 'main::StringToList' : illegal call of non-static member. Line: 7;

I provide you with my main.cpp and main.h files.

Thanks for any

main.cpp

#include "main.h"

int main()
{
main::node *head = main::StringToList("123");

main::node *temp = new main::node;

temp = head;
while (temp->next != NULL)
{
    cout << temp->data;
    temp = temp->next;
}

std::cout << "\nThe program has completed successfully\n\n";
system("PAUSE");
return 0;
}

main::node * StringToList(string number) 
{

int loopTimes = number.length() - 1; 
int looper = 0;         
int *i = new int;       
i = &looper;            
main::node *temp = new main::node;  
main::node *head;               
head = temp;            
for ( i = &loopTimes ; *i >= 0; *i = *i - 1) 
{
    temp->data = number[*i] - 48;   
    main::node *temp2 = new main::node;         
    temp->next = temp2;             
    temp = temp2;                   
}
temp->next = NULL;                  
return head;
}

main.h

#ifndef MAIN_H
#define MAIN_H

#include <iostream>
#include <string>

using namespace std;

class main
{
public:
typedef struct node
{
    int data;
    node *next;
};
node* StringToList (string number);
};

#endif

Upvotes: 2

Views: 12968

Answers (3)

Andreas Fester
Andreas Fester

Reputation: 36630

You need to instanciate your main class and call StringToList as member:

main* m = new main;
main::node *head = m->StringToList("123");
...
delete m;

Upvotes: 2

perilbrain
perilbrain

Reputation: 8187

Since node* StringToList (string number); is not static so you can't call it as main::StringToList("123");

Make an object of main first then call it like

main mn;
mn.StringToList("123");

Otherwise declare node* StringToList (string number); as static node* StringToList (string number);

Upvotes: 0

Bj&#246;rn Pollex
Bj&#246;rn Pollex

Reputation: 76778

You will have to declare StringToList as static for this to work:

static node* StringToList(string number);

In this line:

main::node *head = main::StringToList("123");

You are trying to call StringToList without having first created an object of type main. Since it is a non-static member-function, this does not work. You'd have to do it like this:

main foo;
main::node *head foo.StringToList("123");

Which does not really make sense for your usecase, though.

Upvotes: 1

Related Questions