2014-01-25 85 views
3

我一直在尝试第一次使用C++中的类。我的圈子类和相关的头文件工作正常,然后我移动了一些文件,从那以后不断收到我在下面显示的错误。C++'class'类型重定义

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功能我不认为他们是相关的。在我移动文件位置之前,这些文件没有问题。即使重命名后,我仍然有与上面相同的错误。任何想法来解决这个问题?

+4

我建议你[阅读一些关于C++的书籍](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 –

+0

谢谢,我会浏览一下这个列表。另外,我只能接受一个,但感谢答案,他们都很有帮助。 –

回答

4

问题在于,您正在编译器告诉您的是两次定义类。在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文件中定义。

1

您已经在头文件和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... 
} 
0

删除class CircleObje {,public和th e结束括号};,它应该工作。你已经在.H中定义了你的类,因此不需要在CPP中重新定义它。

此外,你应该写你的成员实现(CPP文件)是这样的:

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

你在头文件中声明,一旦你的班级多次,另一种是重新定义你的类.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; 
}