簡體   English   中英

類類型重定義C ++

[英]Class Type Redefinition C++

我之前見過其他人問過這個問題,但他們收到的答案對他們的程序來說是獨一無二的,遺憾的是我沒有幫助。

首先,我有一個形狀類 - 分為.h和.cpp文件

//Shape.h

    #include <string>
using namespace std;

class Shape
{
private:
    string mColor;

public:
    Shape(const string& color); // constructor that sets the color instance value
    string getColor() const; // a const member function that returns the obj's color val
    virtual double area() const = 0;
    virtual string toString() const = 0;
};

//Shape.cpp

#include "Shape.h"
using namespace std;

Shape::Shape(const string& color) : mColor(NULL) {
    mColor = color;
}
string Shape::getColor() const
{
    return mColor;
}

我的Shape.h類中一直出現錯誤,上面寫着'Shape':'class'類型重定義。 知道為什么我會收到這個錯誤嗎?

include guard添加到頭文件中

#ifndef SHAPE_H
#define SHAPE_H

// put your class declaration here

#endif

初始化成員mColor的方式不正確。 您不能將NULL分配給字符串類型

Shape::Shape(const string& color) : mColor(color) {
}

將虛擬析構函數添加到Shape類,因為它充當具有虛函數的基礎。

另外,請勿在頭文件中使用using指令。

看起來你想在這里寫一個抽象基類,但是你有沒有編譯但是沒有在這里顯示的其他文件?


你必須再包括兩次“shape.h”。 只需使用宏來防止這種情況。

PS:我猜Rectangle是Square的基類,也是繼承Shape。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM