[英]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.