簡體   English   中英

在C ++中從構造函數調用參數

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM