繁体   English   中英

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

[英]C++ text argument to constructor

继续 = 继续;

我不知道如何将 cont 转换为 cont 类型指针。

如果我喜欢这样: this->cont = (char*)cont;

在解构器中,我有异常错误。

那么将 const char 转换为 char* 好还是我需要做得更好(但如何?)?

而且我必须动态分配。

#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;

是“错误的”,因为它实际上并不复制数据; 这也是为什么在失败时在析构函数中delete的原因。 您的回答提到“我必须进行动态分配。”,所以我认为这就是您真正想要的。 在这种情况下,只需使用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
    }
};

首先,您必须使用 new 为指向 char 的指针分配空间。 并在析构函数中释放该空间“delete [] cont”而不是“delete cont”。 但使用 std::string 而不是 char [] 将是一个不错的选择

暂无
暂无

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

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