首页 > 解决方案 > 创建一个带参数的 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 文件中初始化字符串参数的方式。我想我在某处有一个小错字,但我没有发现这段简单的代码有什么问题。任何帮助将非常感激。谢谢

标签: c++constructor

解决方案


由于字符串也是命名空间的一部分,因此您需要对其进行include <string>范围设置。您可以为方便起见。对于标头中的构造函数定义,我认为省略参数名称并仅具有类型会更简洁。std::stdusing namespace std


推荐阅读