问题遇到的现象和发生背景
C++初学阶段,使用VS创建了一个空白项目;
在index.cpp中包含了main函数,另一个util.cpp中包含了其他的方法和类;
现在想要在index.cpp中使用util.cpp中的class,但是却遇到了错误。
问题相关代码,请勿粘贴截图
class Shape {
private:
int width;
int height;
public:
Shape(int w, int h) {
width = w;
height = h;
}
int getArea();
};
int Shape::getArea() {
return width * height;
}
#include <iostream>
#include "util.cpp"
using namespace std;
int main() {
Shape shape(10, 10);
int area = shape.getArea();
cout << "Area is " << area << endl;
return 1;
}
运行结果及报错内容
我的解答思路和尝试过的方法
把util.cpp改成util.h可以解决,但是如果我再新建一个文件cpp文件,也想调用util的class,又会遇到这个重新定义了的问题。