简体   繁体   中英

C++ text argument to constructor

cont = cont;

I don't know how to convert cont to cont type pointer.

If I do like this : this->cont = (char*)cont;

In deconstructor I have exception error.

So is it good to convert const char to char* or I need to do better (but how?) ?

And I have to have dynamic allocate.

#include "pch.h"
#include <iostream>
#include <stdio.h>

using namespace std;
class Matrix {
private:
    int x;
    char *cont;
public:
    Matrix(){
        cout << "aa";
    }
    Matrix(const char *cont) {
        this->cont = cont;
    }
    ~Matrix() {
        delete cont;
    }


};

int main()
{
    Matrix("__TEXT__");
    system("pause");
    return 0;
}
this->cont = cont;

Is "wrong", as in, it doesn't actually copy the data; that's also why delete in your destructor if failing. Your answer mentions "I have to have dynamic allocate.", so I presume that's what you actually wanted. In this case, simply use std::string :

class Matrix {
private:
    int x;
    std::string cont;           // <--- changed type
public:
    Matrix(){
        cout << "aa";
    }
    Matrix(const char *cont)
    : cont(cont) {              // <--- this actually copies
    }
};

first you have to allocate space for a pointer to char using new . And in the destructor deallocate that space " delete [] cont " instead of "delete cont" . but it will be a good choice to use std::string instead of char []

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