简体   繁体   中英

Getting a “Use of undeclared identifier” error

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.

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

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