c++ - 创建一个带参数的 C++ 构造函数
问题描述
我正在刷新如何在 C++ 中编写构造函数,但 C++ 文档版本会引发愚蠢的编译器错误。
我查看了堆栈溢出的其他示例并模仿了它们,但仍然有类似的错误
假设#includes 已经在这里 .h 文件
class Matrix{
private:
//eventually going to create 2d vector here
public:
// from: http://www.cplusplus.com/doc/tutorial/classes/
Matrix (string);
//another way shown from other examples
Matrix (string filename);
};
.cpp
Matrix::Matrix(string filename){
int num = 0;
string line;
ifstream matrix_file(filename);
if(matrix_file.is_open()){
while(getline(matrix_file, line)){
stringstream extract(line);
while(extract >> num){
cout << num << " ";
}
cout << '\n';
}
matrix_file.close();
}
}
主文件
int main(int argc, char *argv[]){
string filename = argv[1];
Matrix grid (filename);
return 0;
}
我期待在调用构造函数时创建对象,它会打印出文件中的值。但是在编译时,我得到:
matrix.h:6:12: warning: unnecessary parentheses in declaration of ‘string’ [-Wparentheses]
Matrix (string);
^
matrix.h:6:19: error: field ‘string’ has incomplete type ‘Matrix’
Matrix (string);
^
matrix.h:2:7: note: definition of ‘class Matrix’ is not complete until the closing brace
class Matrix{
或者
matrix.h:6:19: error: expected ‘)’ before ‘filename’
Matrix (string filename);
~ ^~~~~~~~~
)
main.cpp: In function ‘int main(int, char**)’:
main.cpp:11:24: error: no matching function for call to ‘Matrix::Matrix(std::__cxx11::string&)’
Matrix grid (filename);
取决于我在 .h 文件中初始化字符串参数的方式。我想我在某处有一个小错字,但我没有发现这段简单的代码有什么问题。任何帮助将非常感激。谢谢
解决方案
由于字符串也是命名空间的一部分,因此您需要对其进行include <string>
范围设置。您可以为方便起见。对于标头中的构造函数定义,我认为省略参数名称并仅具有类型会更简洁。std::
std
using namespace std
推荐阅读
- javascript - 我如何制作 react-create-app 来缩小我的代码?
- error-handling - VBScript - 验证输入是 IP,每八位字节 3 位
- processing - 有条件地改变圆圈大小会创建多个圆圈
- javascript - React Native - 创建 N 个动画值
- javascript - 通过 Node.js JSON 输出从 Asana Task API 中提取特定项目 ID
- python - Python 无法从照片 Linux 中提取数字
- python - 按顺序迭代 DataFrame 日期组,参考上一组
- c - char ** 指针中的段错误(学习 malloc 和指针的用法)
- c - 从文件中读取数据的问题,一个简单的C语言代码
- json - Dataweave 2.0 - XML 到 JSON 数组:在不同 XML 结构中按 id 分组