No declaration matches с ошибка

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

Tharisha Perera's user avatar

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 Varshavchik's user avatar

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
Shape.h
#ifndef SHAPE_H
#define SHAPE_H


class Shape
{
    public:
        /** constructors */
        virtual float getArea()= 0;
        virtual float getPerimeter() = 0;

};

#endif // SHAPE_H


  circle.h

#ifndef Circle_H
#define Circle_H
#include "Shape.h"
const float PI = 3.14159265358979323846;

using namespace std;
                                   
class Circle: public Shape
{
 protected:
    float radius;                  

 public:                          
	Circle(float r)     
        {
        float getRadius();
        void setRadius(float radius);
       }          
};
#endif CIRCLE_H

Circle.cpp
#include "Circle.h"
#include "Shape.h"
#include <iostream>
using namespace std;


Circle::Circle(float r)
    {
    radius = r;
    }

    float Circle::getRadius()const
    {
    return radius;
    }

    void Circle::setRadius(float r)
    {
    radius = r;
    }

    float Circle::Shape()const
    {
    return PI * radius * radius;
    }

    float Circle::getPerimeter()const
    {
	return (2.0 * PI * radius);
    }

main.cpp
#include <iostream>
#include "Circle.h"
#include "Square.h"
#include "Triangle.h"

using namespace std;

int main()
{

float radius;
float getArea;
float getPerimeter;


cout << "----------------------------------------------" << endl << endl;
cout << "Calculations for a Circle" << endl << endl;
cout << "----------------------------------------------" << endl << endl;

cout << "Let's find the Area and Perimeter of a Circle:" << endl;
cout << endl;
        cout << "Enter the radius for the Circle: ";
        cin >> radius;
        cout << endl;
        //getArea = (PI * radius *radius);
        Circle circle;
        circle.getRadius();
        cout <<  "The area of the circle is: " << circle.getArea(); << "nn";
        cout << endl;
        cout <<  "AND"  << "nn"<< endl;
        cout <<  "The perimeter of the circle is: " << circle.getPerimeter(); << "nn";
cout << endl;
   return 0;
}

[/code]

Here is the code with all errors removed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#ifndef SHAPE_H
#define SHAPE_H


class Shape
{
    public:
        /** constructors */
        virtual float getArea()= 0;
        virtual float getPerimeter() = 0;

};

#endif // SHAPE_H


#ifndef Circle_H
#define Circle_H
const float PI = 3.14159265358979323846;

using namespace std;
                                   
class Circle: public Shape
{
 protected:
    float radius;                  

 public:                          
	Circle(float r);
        float getRadius();
        void setRadius(float radius);

        virtual float getArea() override;
        virtual float getPerimeter() override;
};
#endif 

#include <iostream>
using namespace std;


Circle::Circle(float r)
    {
    radius = r;
    }

    float Circle::getRadius()
    {
    return radius;
    }

    void Circle::setRadius(float r)
    {
    radius = r;
    }

    float Circle::getArea()
    {
    return PI * radius * radius;
    }

    float Circle::getPerimeter()
    {
	return (2.0 * PI * radius);
    }

#include <iostream>

using namespace std;

int main()
{

float radius;
float getArea;
float getPerimeter;


cout << "----------------------------------------------" << endl << endl;
cout << "Calculations for a Circle" << endl << endl;
cout << "----------------------------------------------" << endl << endl;

cout << "Let's find the Area and Perimeter of a Circle:" << endl;
cout << endl;
        cout << "Enter the radius for the Circle: ";
        cin >> radius;
        cout << endl;
        //getArea = (PI * radius *radius);
        Circle circle{10};
        circle.getRadius();
        cout <<  "The area of the circle is: " << circle.getArea() << "nn";
        cout << endl;
        cout <<  "AND"  << "nn"<< endl;
        cout <<  "The perimeter of the circle is: " << circle.getPerimeter() << "nn";
cout << endl;
   return 0;
}

Note that the definition of a function must match the prototype. I.e. this

float Circle::getRadius()const
->

1
2
3
4
5
6
7
8
class Circle: public Shape
{
 protected:
    float radius;                  

 public:                          
	Circle(float r);
        float getRadius() const; // Note: 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

    cout << "----------------------------------------------" << endl << endl;
    cout << "Calculations for a Circle" << endl << endl;
    cout << "----------------------------------------------" << endl << endl;

    cout << "Let's find the Area and Perimeter of a Circle:" << endl;
    cout << endl;
    cout << "Enter the radius for the Circle: ";
        cin >> radius;
    cout << endl;
    try{
        if(radius ==0)
        {
         throw 99;
        }
        Circle cir{10};
        cir.getRadius();
    }
    catch(float x)
    {
         cout <<"EXCEPTION: You cannot use 0 as your radius";
    }
        cout <<  "The area of the circle is: " << cir.getArea() << "nn";
        cout << endl;
        cout <<  "AND"  << "nn"<< endl;
        cout <<  "The perimeter of the circle is: " << cir.getPerimeter() << "nn";
        cout << endl;

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
cin >> radius;
if (radius == 0)
{
    cout << "You cannot use 0 as your radiusn";
}
else
{
        Circle cir{10};
        cout <<  "The area of the circle is: " << cir.getArea() << "nn";
        cout << endl;
        cout <<  "AND"  << "nn"<< endl;
        cout <<  "The perimeter of the circle is: " << cir.getPerimeter() << "nnn";
}

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

Другие решения

Других решений пока нет …

Понравилась статья? Поделить с друзьями:
  • No connection with stb server триколор как устранить ошибку
  • No columns to parse from file ошибка
  • No column was specified for column ошибка
  • No coffee beans off 8 ошибка перевод на русский
  • No changes were made to your device gapps ошибка