简体   繁体   中英

calling a parameter from the constructor in c++

I am trying to use something that in the constructor but I get compile error here is the constructor

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

Here is the implimintation of the function

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

And here is the header(my class)

 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

The problem is here

if (strcmp(type, "Any") == 0)

Ia m new to C++ and I don't get whats the problem I get no suitable conversion function from std::string to const char * exists

A std::string is not a const char* . It cannot be implicitly converted to one, and you can't pass it to strcmp as if it were. But you don't need to. std::string is sane type, and you can just compare directly:

if (type == "Any") {
}

For a situation where you do need a "C-string" view of a std::string , it has a member function named c_str() that returns such a pointer. But again, comparison is not such a situation.

[hint] if you're new to C++,

  • try to not use pointers, anywhere
  • try to use a library instead of implementing matrix ( eigen is a good one)
  • do read up on how bad it can get if your code contains new , and how you can benefit from using std::vector instead

This small investment will save you tons of headaches in the (near) future.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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