0

Look at the following code...

#include <iostream>
#include <cstring>

using namespace std;

class string
{
      char *p;
      int len;
public:
       string(char *);
       void show()
       {
            cout<<p<<endl;
       }
};

string :: string(char *p)
{
       len = strlen(p);
       this.p = new char[len+1];
       strcpy(this.p, p);
}

int main()
{
    string s1, s2;
    char *nm1 = "IBM PC";
    char *nm2 = "Apple computers";
    s1 = string(nm1);
    s2 = nm2;
    s1.show();
    s2.show();
    char ch;
    cin>>ch;
    return 0;
}

In the above code everything is theoretically correct. But shows the following bug..

F:\Dev-Cpp\basic.cpp:18: error: `string' has not been declared

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by lipun4u
1

string is not a good name because that name is already used for the std::string class. At the very least you should put your class in a namespace. I do not have Dev-C++, so I cannot reproduce your error, but I would guess that is the cause of the error.

There are also other errors. One that might be confusing is that this is a pointer, so you cannot use the . operator like that to get to members. Use the -> operator instead.

Edited by Tom Gunn: n/a

0

Thanx for helping me....

finally problem solved...

#include <iostream>
#include <cstring>

using namespace std;

class string1
{
      char *p;
      int len;
public:
       string1():p(NULL), len(0) {}
       string1(char *);
       void show()
       {
            cout<<p<<endl;
       }
};

string1 :: string1(char *p)
{
       len = strlen(p);
       this->p = new char[len+1];
       strcpy(this->p, p);
}

int main()
{
    string1 s1, s2;
    char *nm1 = "IBM PC";
    char *nm2 = "Apple computers";
    s1 = string1(nm1);
    s2 = nm2;
    s1.show();
    s2.show();
    char ch;
    cin>>ch;
    return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.