簡體   English   中英

C ++'class'類型重定義

[英]C++ 'class' type redefinition

我第一次嘗試使用c ++中的類。 我的圈子類和相關的頭文件工作正常,然后我移動了一些文件,然后繼續得到我在下面顯示的錯誤。

c:\circleobje.cpp(3): error C2011: 'CircleObje' : 'class' type redefinition

c:\circleobje.h(4) : see declaration of 'CircleObje'

CircleObje.h

#ifndef CircleObje_H
#define CircleObje_H
class CircleObje
{
public:
void setCol(float r, float g, float b);
void setCoord(int x, int y);
float getR();
float getG();
float getB();
int getX();
int getY();
};

#endif

CircleObje.cpp

#include "CircleObje.h"

class CircleObje {

float rVal, gVal, bVal;
int xCor, yCor;

public:

void setCol(float r, float g, float b)
{
    rVal = r;
    gVal = g;
    bVal = b;
}

void setCoord(int x, int y)
{
    xCor = x;
    yCor = y;
}

...
};

我沒有復制所有.cpp函數,因為我認為它們不相關。 在移動文件位置之前,這些文件沒有問題。 即使重命名后我仍然有與上面相同的錯誤。 有什么想法來解決這個問題嗎?

問題是你正在編譯器告訴你兩次定義類。 在cpp中,您應該提供函數的定義,如下所示:

MyClass::MyClass() {
  //my constructor
}

要么

void MyClass::foo() {
   //foos implementation
}

所以你的cpp應該是這樣的:

void CirleObje::setCol(float r, float g, float b)
{
    rVal = r;
    gVal = g;
    bVal = b;
}

void CircleObje::setCoord(int x, int y)
{
    xCor = x;
    yCor = y;
}

...

並且所有類變量都應該在類的.h文件中定義。

你在頭文件中多次聲明你的類,而在.cpp文件中再次聲明你的類,這是重新定義你的類。

CircleObje.h

#ifndef CircleObje_H
#define CircleObje_H
class CircleObje
{
public:
void setCol(float r, float g, float b);
void setCoord(int x, int y);
float getR();
float getG();
float getB();
int getX();
int getY();
public:
float rVal, gVal, bVal;
int xCor, yCor;



};

#endif



CircleObje.cpp

#include "CircleObje.h"



void CircleObje::void setCol(float r, float g, float b)
{
    rVal = r;
    gVal = g;
    bVal = b;
}

void CircleObje::setCoord(int x, int y)
{
    xCor = x;
    yCor = y;
}

您已在頭文件和cpp中定義了兩次類,因此在.cpp中,編譯器會看到兩個定義。 刪除.cpp上類的定義。

類函數應該以這種方式在cpp中實現:

<return_type> <class_name>::<function_name>(<function_parameters>)
{
    ...
}

考慮這個示例類:

//foo.hpp

struct foo
{
    int a;

    void f();
}

該類在foo.cpp文件中實現:

#include "foo.hpp"

void foo::f()
{
    //Do something...
}

刪除class CircleObje {publicclass CircleObje { bracket }; 它應該工作。 您已經在.H中定義了您的類,因此無需在CPP中重新定義它。

此外,您應該編寫您的成員實現(在CPP文件中),如下所示:

float CircleObje::getR() { /* your code */ } 

暫無
暫無

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

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