'(' 标记之前的预期构造函数、析构函数或类型转换

新手上路,请多包涵

编译 polygone.hpolygone.cc 给出错误:

 polygone.cc:5:19: error: expected constructor, destructor, or type conversion before ‘(’ token

代码:

 //polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

# include <iostream>

class Polygone {

    public:
        Polygone(){};
        Polygone(std::string fichier);

};

# endif

//polygone.cc
# include <iostream>
# include <fstream>
# include "polygone.h"

Polygone::Polygone(string nom)
{
    std::ifstream fichier (nom, ios::in);
    std::string line;

    if (fichier.is_open())
    {
        while ( fichier.good() )
        {
            getline (fichier, line);
            std::cout << line << std::endl;
        }
    }
    else
    {
        std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
    }
}

//ifstream fich1 (argv[1], ios::in);

我的猜测是编译器没有将 Polygone::Polygone(string nom) 识别为构造函数,但是,如果确实如此,我不知道为什么。

有什么帮助吗?

原文由 Marconius 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 893
2 个回答

标头中的第一个构造函数不应以分号结尾。 #include <string> 标题中缺少。 string std:: 的条件。这些都是简单的语法错误。更重要的是:当你应该使用引用时,你没有使用。您使用 ifstream 的方式也被破坏了。我建议在尝试使用它之前学习 C++。

让我们解决这个问题:

 //polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>

Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);

  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

原文由 pmr 发布,翻译遵循 CC BY-SA 4.0 许可协议

这不仅是一个“新手”场景。在重构一个类以删除一些构造函数参数时,我刚刚遇到了这个编译器消息(GCC 5.4)。我忘了更新声明和定义,编译器吐出了这个不直观的错误。

底线似乎是这样的:如果编译器无法将定义的签名与声明的签名匹配,它会认为定义不是构造函数,然后不知道如何解析代码并显示此错误。这也是 OP 发生的情况: std::stringstring 的类型不同,因此声明的签名与定义的签名不同,并且此消息被吐出。

作为旁注,如果编译器寻找几乎匹配的构造函数签名并且在找到一个建议参数不匹配而不是给出此消息时会很好。

原文由 Bob Kocisko 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题