单继承c++和头文件

Single Inheritance C++ and header files

本文关键字:文件 c++ 继承 单继承      更新时间:2023-10-16

我得到一个

expected class-name before '{' token
以下代码 中的

咸水鱼.h头文件:

#ifndef SALTWATERFISH_H
#define SALTWATERFISH_H

class saltwaterfish: public fish
{
public:
    saltwaterfish();
    float GetUnitPrice();
    float GetWeight();
};
#endif // SALTWATERFISH_H

这是定义

头文件的正确方法吗?

"咸水鱼是鱼的一个亚纲" ?

我在咸水鱼。cpp中唯一的东西是

#include "fish.h"
#include "saltwaterfish.h"

fish.cpp类:

#include "fish.h"
#include <iostream>
#include "freshwaterfish.h"
#include "saltwaterfish.h"
using namespace std;
fish::fish()
{
};
float fish::CalculatePrice()
{
    return GetUnitPrice()*GetWeight();
}
float fish::GetUnitPrice()
{
    return 1.0;
}
float fish::GetWeight()
{
    return 1.0;
}

在saltwaterfish.h中包含fish.h头文件

//saltwaterfish.h
#include"fish.h"
#ifndef SALTWATERFISH_H
#define SALTWATERFISH_H

class saltwaterfish: public fish
{
public:
    saltwaterfish();
    float GetUnitPrice();
    float GetWeight();
};
#endif // SALTWATERFISH_H

编译器没有看到Fish是一个类,因此出现错误。

你应该把

#include "fish.h"

在头文件本身。(saltwaterfish.h)

否则这段代码将无法访问fish类。

好运。

这个错误的意思是"{之前的东西应该是一个类名,但它不是。"所以'fish'不是一个类名。查找fish类的声明,并确保在此声明之前加载了它。