Reputation: 17
I am to create a custom String
class in C++ with different methods in it.
The problem I have is that I get a "Use of undeclared identifier" error with a method that is declared in another file:
#include <iostream>
#include "String.h"
int main() {
std::cout << "Hello World!\n";
char str[] = "Today I am happy.";
cout<<strlen(str); // error
strlwr(str); //error
}
This is the other file, String.h
:
#include <iostream>
using namespace std;
class Strings
{
public:
char *s;
Strings(char *a){
int l=0;
for(int i=0;a[i]!='\0';i++)
l++;
/*The length of string a*/
s=new char[l+1];
for(int i=0;a[i]!='\0';i++)
s[i]=a[i];
}
void strlwr(char *s1){ //method
for(int i=0;s1[i]!='\0';i++)
{
if(s1[i]>='A' && s1[i]<='Z')
s1[i]=(char)(s1[i]+32);
}
for(int i=0;s1[i]!='\0';i++)
cout<<s1[i];
}
int strlen(char *s1) //method
{
int l=0;
for(int i=0;s1[i]!='\0';i++)
{
l++;
}
return l;
}
int strcmp(char *s1,char *s2){
while(*s1 != '\0' && *s2 != '\0' && *s1 == *s2){
s1++;
s2++;
}
if(*s1 == *s2){
cout<<"They are equal";
return 0;
}
else if(*s1 >= *s2)
return 1;
else
return -1;
}
};
This has worked fine with other programs. I don't know why I have this problem now.
Upvotes: 0
Views: 1043
Reputation: 22074
If these functions are independent of the class, you can declare them static
.
static void strlwr(char *s1){ //method
static int strlen(char *s1) //method
And them use them like this:
cout<<String::strlen(str); // error
String::strlwr(str); //error
Upvotes: 1