从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)
ia m新的C ,我不知道我没有从std::string
到const char *
的合适转换功能
a std::string
不是 const char*
。它不能隐式转换为一个,并且您不能将其传递给strcmp
。但是您不需要。std::string
是理智的类型,您可以直接比较:
if (type == "Any") {
}
对于您需要需要 a的" c弦"视图的情况,它具有一个名为 c_str()
的成员函数,该函数返回了这样的指针。但同样,比较并不是这种情况。
[提示]如果您不熟悉C ,
- 尝试不使用指针,任何地方
- 尝试使用库而不是实现矩阵(
eigen
是一个很好的矩阵) - 请仔细阅读,如果您的代码包含
new
,以及如何从使用std::vector
而不是使用CC_11而受益
这项小型投资将为您节省(近)将来的大量头痛。
相关文章:
- C++:使用运算符 = 调用多参数构造函数
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 好奇的混合与可变参数构造函数
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 为什么我们需要创建一个单参数构造函数来使用临时的无名称对象
- 在可变参数构造函数中初始化常量数组
- C++ 显式多参数构造函数歧义
- 零一参数构造函数
- 可变参数构造函数中的 SFINAE
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 可变参数类模板和可变参数构造函数
- 确保模板参数类型与其可变参数构造函数的类型匹配
- C++默认参数构造函数与内联初始化优先级
- 如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?
- 自动存储中没有无参数构造函数的类对象和异常
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 如何在C++中调用无参数构造函数
- 在 c++ 中具有多个参数构造函数的模板类存在问题
- 可变参数构造函数优先于用户提供的移动构造函数,除非默认
- 如何从可变参数构造函数参数构造任何对象?