简体   繁体   English

构造函数的 C++ 文本参数

[英]C++ text argument to constructor

cont = cont;继续 = 继续;

I don't know how to convert cont to cont type pointer.我不知道如何将 cont 转换为 cont 类型指针。

If I do like this : this->cont = (char*)cont;如果我喜欢这样: 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?) ?那么将 const char 转换为 char* 好还是我需要做得更好(但如何?)?

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.这也是为什么在失败时在析构函数中delete的原因。 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 :在这种情况下,只需使用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 .首先,您必须使用 new 为指向 char 的指针分配空间。 And in the destructor deallocate that space " delete [] cont " instead of "delete cont" .并在析构函数中释放该空间“delete [] cont”而不是“delete cont”。 but it will be a good choice to use std::string instead of char []但使用 std::string 而不是 char [] 将是一个不错的选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM