开发者

issue with pointers and constructors

The following code doesn't work:

class String{
public:
    char* str;
    int* counter;

    String(){
        str = NULL;
        counter = new int;
        *counter = 1;
    };
    String(const char* str1){
        String();
        str = new char[strlen(str1)+1];
        strcpy(str, str1);
    };

开发者_如何转开发
 };

I've changed the call to the empty constructor and replaced it with its internals, and now the following code works:

class String{
public:
    char* str;
    int* counter;

    String(){
        str = NULL;
        counter = new int;
        *counter = 1;
    };
    String(const char* str1){
        //String();
        str = new char[strlen(str1)+1];
        strcpy(str, str1);
        counter = new int;
        *counter = 1;
    };

Can you please suggest why?

Thanks, Li.


"Doesn't work" is not a good description of the problem. But you apparently tried to invoke a constructor from another one. That's called constructor delegation and is not (yet) supported by C++.

BTW, a class like this should get a user-defined copy constructor, assignment operator and destructor.


It seems to me you are trying to invoke a constructor from another constructor of the same class, like you would in C# for example. Unfortunately you cannot do this in C++ (at least no easy way I know of). You need to either have a private method or duplicate the code.


In the current C++, constructors cannot call each other. That's called "chaining constructors", or "delegating constructors" and is supported by the new C++0x standard but with a different syntax than the one you are using.

Off-topic, why do you use a pointer to int for the counter?


Calling String(); actually creates a temporary object and then throws it away again. It won't call the other constructor.


The call 'String();' creates an unnamed temporary object of type String that is destroyed immediately. The second code snippet is fine.

However you should really relook at the members of your class. Use std::string instead of raw char pointer. Also int *counter does not look very intuitive


You are allowed to do something like this:

class String{

public:
    char* str;
    int* counter;

private:
    void initialize() {
        str = NULL;
        counter = new int;
        *counter = 1;
    }
public: 
    String(){
        initialize();
    };
    String(const char* str1){
        initialize();
        str = new char[strlen(str1)+1];
        strcpy(str, str1);
    };


 };


  • why is the counter a pointer ?

What does not work ? compilation error ?

Probably calling the constructor inside another is not well supported on your compiler ?

what platform ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜