Mar*_*ius 12 c++ constructor class
编译polygone.h并polygone.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)为构造函数,但是,如果确实如此,我不知道为什么.
有帮助吗?
这不仅仅是一个“新手”场景。在重构类以删除一些构造函数参数时,我刚刚遇到了这个编译器消息(GCC 5.4)。我忘记更新声明和定义,编译器吐出这个不直观的错误。
底线似乎是这样的:如果编译器无法将定义的签名与声明的签名相匹配,它会认为该定义不是构造函数,然后不知道如何解析代码并显示此错误。这也是 OP 发生的情况: std::string与类型不同,string因此声明的签名与定义的签名不同,并且此消息被吐出。
作为旁注,如果编译器寻找几乎匹配的构造函数签名并且在发现一个建议参数不匹配而不是给出此消息时,那就太好了。
标头中的第一个构造函数不应以分号结尾。#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)
| 归档时间: |
|
| 查看次数: |
85320 次 |
| 最近记录: |