![](/img/trans.png)
[英]C++ Base constructor calling with parameter that will be constructed in the derived constructor
[英]calling a parameter from the constructor in c++
我正在嘗試在構造函數中使用某些東西,但是這里出現編譯錯誤
Matrix::Matrix(int rows, int cols, std::string matType) {
type = matType;
row = rows;
col = cols;
array= new double*[row];
for (int i = 0; i < row; ++i)
array[i] = new double[col];
for (int i = 0; i < rows; i++)
for (int j = 0; j<cols; j++)
array[i][j] = 0;}
這是功能的含義
void Matrix::setElement(int i, int j, double data) {
if (i > row || j > col)
return;
if (strcmp(type, "Any") == 0) {//here is the problem i cant use type i get compile error
array[i][j] = data;
}
if (strcmp(type, "Arrowhead") == 0) {
if (data != 0 && i == 0) {
array[i][j] = data;
}
if (data != 0 && j == 0)
array[i][j] = data; {
}
if (data != 0 && j == i) {
array[i][j] = data;
}
} }
這是標題(我的課)
class Matrix {
public:
string type;
int row, col;
double **array;
public:
Matrix(int rows, int cols, std::string matType); // set the (i,j) element to be 'data'
void setElement(int i, int j, double data); // return the (i,j) element
問題在這里
if (strcmp(type, "Any") == 0)
我是C ++的新手,但我沒有得到什么問題,我沒有從std::string
轉換為const char *
合適轉換函數const char *
存在
std::string
不是const char*
。 它不能隱式轉換為1,也不能像將其傳遞給strcmp
一樣。 但是您不需要。 std::string
是理智的類型,您可以直接進行比較:
if (type == "Any") {
}
對於確實需要 std::string
的“ C字符串”視圖的情況,它具有一個名為c_str()
的成員函數,該函數返回這樣的指針。 但是同樣,比較不是這種情況。
[提示]如果您不熟悉C ++,
eigen
是一個很好的方法) new
嚴重程度以及使用std::vector
可以從中受益的信息 這筆小小的投資將在(不久的將來)為您省去許多麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.