跨C ++中多个文件的类 [英] Classes across multiple files in C++

查看:378
本文介绍了跨C ++中多个文件的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎100%确定我有这两个类的语法正确,但我得到以下错误:

I'm almost 100% sure I have the syntax right in both of these classes, however I'm getting the following errors:

对于CShape.cpp - error C2011:'CShape':'class'type redefinition
对于CCircle.cpp - 错误CS2504:'CShape':基类未定义

For CShape.cpp - "error C2011: 'CShape' : 'class' type redefinition" For CCircle.cpp - "error CS2504: 'CShape': base class undefined"

这里是CShape.cpp的完整代码

Here is the full code for CShape.cpp

#include <iostream>
using namespace std;

class CShape
{
protected:
    float area;
    virtual void calcArea();
public:
    float getArea()
    {
        return area;
    }
}

这里是CCircle.cpp



And here is the code for CCircle.cpp

#include <iostream>
#include "CShape.cpp"
#define _USE_MATH_DEFINES
#include "math.h"
using namespace std;

class CCircle : public CShape
{
protected:
    int centerX;
    int centerY;
    float radius;
    void calcArea()
    {
        area = M_PI * (radius * radius);
    }
public:
    CCircle(int pCenterX, int pCenterY, float pRadius)
    {
        centerX = pCenterX;
        centerY = pCenterY;
        radius = pRadius;
    }
    float getRadius()
    {
        return radius;
    }
}

正如你所看到的,CShape是一个基类CCircle被承担继承。我对C ++很新,所以我可以有文件结构错误(也许基地应该在一个头文件?),如果这样的事情很重要。

As you can see, CShape is the base class that CCircle is suppsoed to inherit from. I'm pretty new to C++, so I could have the file structures wrong (maybe the base is supposed to be in a header file?), if something like that matters.

推荐答案

从不#include .cpp文件;这将导致你得到的那种重定义错误。
$ b $ b

Never #include .cpp files; that will lead to the kind of redefinition errors you are getting. Instead, declare the class in a header file and #include that one, and define the class methods in a .cpp file.

// CShape.h
class CShape
{
protected:
    float area;
    virtual void calcArea();
public:
    float getArea();
}

// CShape.cpp
#include "CShape.h"
#include <iostream>
using namespace std;

float CShape::getArea() {
    return area;
}

您应该拆分CCircle类似,CCircle.h应该#include CShape。 h和CCircle.cpp应该#include CCircle.h。

You should split up CCircle similarly - and CCircle.h should #include CShape.h, and CCircle.cpp should #include CCircle.h.

这篇关于跨C ++中多个文件的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆