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

Mar*_*ius 12 c++ constructor class

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

polygone.cc:5:19: error: expected constructor, destructor, or type conversion before ‘(’ token
Run Code Online (Sandbox Code Playgroud)

码:

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

# include <iostream>

class Polygone {

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

};

# endif
Run Code Online (Sandbox Code Playgroud)

//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);
Run Code Online (Sandbox Code Playgroud)

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

有帮助吗?

Bob*_*sko 8

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

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

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


pmr*_*pmr 6

标头中的第一个构造函数不应以分号结尾。#include <string>标头中缺少。在.cpp文件中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
Run Code Online (Sandbox Code Playgroud)

//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 tidy 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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 难道不是要用它来学习它的最好方法吗?(这并不是建议将结果发布到SO是修复语法错误的最佳方法。) (33认同)
  • 我同意在深入研究编码之前最好对C ++有更好的了解,但是我正在争先恐后地完成此任务。这也解释了为什么我通过使用SO来“学习” C ++来“作弊”。 (2认同)