I’m practicing OOP with C++ and when I try to inherit from a superclass to a subclass, I’m getting an error «No Declaration Matches …».
class RentVehicle{
protected:
string brand, model, color;
int model_yr, no_days;
float starting_km, ending_km;
public:
void recordData();
void DisplayData();
float calRent();
void displayRent(float);
};
class Car:protected RentVehicle{
protected:
public:
string body_type;
void setData();
};
and I’m getting the error here saying * No declaration matches ‘void Car::recordData()’ *
void Car::recordData(){
fstream car;
car.open("RentData.txt", ios::app);
car<<setw(10)<<brand<<setw(10)<<model<<setw(10)<<body_type<<setw(10)<<color<<setw(10)<<model_yr<<setw(10)<<no_days<<setw(10)<<kms<<endl;
car.close();
}
How to fix this?
asked May 6, 2021 at 12:44
3
Car
does not have a method called recordData
, this is RentVehicle
‘s method:
void RentVehicle::recordData(){
// ...
However, RentVehicle
does not have a body_type
member, that’s the subclass’s member, so you won’t be able to assign to it here.
So perhaps you should declare recordData
in Car
‘s class definition, in the first place.
answered May 6, 2021 at 12:46
Sam VarshavchikSam Varshavchik
112k5 gold badges91 silver badges146 bronze badges
1
- Forum
- Beginners
- No declaration matches
No declaration matches
I am trying to find the area and perimeter of a Circle using multiple files. I keep getting an error for no declaration matches. I have been working on this for over a week and cannot figure out what I am doing wrong.
|
|
[/code]
Here is the code with all errors removed:
|
|
Note that the definition of a function must match the prototype. I.e. this
float Circle::getRadius()const
->
|
|
I made the suggested corrections and added an exception and now I get the following error:
main.cpp:50:51: error: ‘cir’ was not declared in this scope
|
|
Last edited on
could you post the full code?
Circle cir is declared within the scope of the try block. It is not visible to the logic in your catch block or outer code.
Are you required to use exceptions here for academic purposes? If not, I would just change your logic into an if/else chain.
|
|
Alternatively, you could have the constructor of Circle throw.
Last edited on
Yes. I am required to add two custom exceptions which inheirt from std:exception.
Topic archived. No new replies allowed.
В общем, пишу приложуху/учу qt, и тут не с того не с сего ошибка no declaration matches ‘void MainWindow::on_Dds_button_clicked()’, пытался найти решение, не получилось. Вот код:
main.cpp
#include "mainwindow.h"
#include <iostream>
#include <QLabel>
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp
#include "mainwindow.h"
#include <iostream>
#include "./ui_mainwindow.h"
#include <QFileDialog>
using namespace std;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_Dds_button_clicked()
{
QString downloadsPath = QFileDialog::getExistingDirectory(0, "Выбор папки", "C:\");
ui->tlabel->setText(downloadsPath);
}
void MainWindow::on_Ds_button_clicked()
{
QString tfileDirPath = QFileDialog::getExistingDirectory(0, "Выбор папки", "C:\");
}
No declaration matches error — C++
Hey guys, I’m doing an assignment for my Comp Sci 2 class, and I’m getting this error:
crewmember.cpp:30:8: error: no declaration matches 'std::__cxx11::string CrewMember::toString()' string CrewMember::toString(){ crewmember.h:23:10: note: candidate is: 'void CrewMember::toString()' crewmember.h:5:7: note: 'class CrewMember' defined here class CrewMember{ ^~~~~~~~~~
I’ve exhausted StackOverflow and can’t find the answer. Here is some of my code:
main.cpp
CrewMember cm1("Johnny Appleseed", 1234, "Pilot"); cout << "CM1: " << cm1.toString() << endl;
crewmember.h
#include <string> using namespace std; class CrewMember{ private: string name = ""; int IDNum = 0; string type = ""; public: CrewMember(string name, int IDNum, string type); string GetName(); void SetName(string name); int GetIDNum(); void SetIDNum(int IDNum); string GetType(); void SetType(string type); string toString(); };
crewmember.cpp
#include "crewmember.h" CrewMember::CrewMember(string name, int IDNum, string type){ this->name = name; this->IDNum = IDNum; this->type = type; } string CrewMember::GetName(){ return name; } void CrewMember::SetName(string name){ this->name = name; } int CrewMember::GetIDNum(){ return IDNum; } void CrewMember::SetIDNum(int IDNum){ this->IDNum = IDNum; } string CrewMember::GetType(){ return type; } void CrewMember::SetType(string type){ this->type = type; } string CrewMember::toString(){ return name + " ID:" + to_string(IDNum) + " " + type; }
I can’t for the life of me figure out why I’m getting this error when I have the same setup for my Date class and that works. I would love some insight if anyone has come across this before… Thanks.
Archived post. New comments cannot be posted and votes cannot be cast.
Следующее не компилируется под g ++ 8.1.0 на CentOS 7:
hey.h
#pragma once
#include <iostream>
#include <type_traits>
class Valid {};
class Invalid {};
struct Hey
{
template<typename T>
static constexpr bool is_valid() { return std::is_same_v<T, Valid>; }
template<typename T, std::enable_if_t<is_valid<T>()>* = nullptr>
void howdy() const;
};
template<typename T, std::enable_if_t<Hey::is_valid<T>()>*>
void Hey::howdy() const
{
std::cout << "Howdy" << std::endl;
}
Выход компилятора:
In file included from hey.cpp:1:
hey.h:18:8: error: no declaration matches ‘void Hey::howdy() const’
void Hey::howdy() const
^~~
hey.h:14:10: note: candidate is: ‘template<class T, std::enable_if_t<is_valid<T>()>* <anonymous> > void Hey::howdy() const’
void howdy() const;
^~~~~
hey.h:8:8: note: ‘struct Hey’ defined here
struct Hey
^~~
Удивительно, но все, что мне нужно сделать, чтобы правильно скомпилировать и получить желаемое поведение, это добавить typedef в Hey:
hey.h (исправлено, первые скучные строки пропущены)
struct Hey
{
template<typename T>
static constexpr bool is_valid() { return std::is_same_v<T, Valid>; }
template<typename T>
using EnableType = std::enable_if_t<is_valid<T>()>;
template<typename T, EnableType<T>* = nullptr>
void howdy() const;
};
template<typename T, Hey::EnableType<T>*>
void Hey::howdy() const
{
std::cout << "Howdy" << std::endl;
}
hey.cpp
#include "hey.h"
int main(int, char**)
{
Hey hey;
hey.howdy<Valid>();
// Adding this line breaks the build, as it should:
// hey.howdy<Invalid>();
return 0;
}
После многих настроек я сузил ситуацию с ошибкой компилятора до того, что 1) is_valid()
является членом Hey
и 2) howdy()
объявлен внутри Hey
Тело, но определено снаружи. Если вы удалите using
и сделать is_valid()
автономная функция вне Hey
Нет проблем с компиляцией. Если вы удалите using
и определить howdy()
внутри определения класса также нет проблем с компиляцией. Но когда howdy()
определяется вне определения класса, is_valid()
объявляется внутри определения класса, а using
нет, компилятор выходит из строя. Это правильное поведение? Я смотрю на ошибку компилятора?
3
Решение
Соответствие выражений в объявлениях шаблона основано на эквивалентность, концепция, основанная на правиле одного определения. Чтобы два выражения считались эквивалентными, они должны быть идентичны токену по токену по модулю переименования параметров шаблона.
Выражения is_valid<T>()
а также Hey::is_valid<T>()
не эквивалентны (у второго есть два токена, у первого нет), поэтому компилятору не требуется их сопоставлять.
Hey::EnableType<T>
является типом и не подчиняется строгим правилам эквивалентности выражений.
2
Другие решения
Других решений пока нет …