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,又会遇到这个重新定义了的问题。
你这个是编程前期最容易遇到的问题,重复引用
也就是你一个定义 X 被 A B 同时引用,然后C 里面又同时引用了A B,这样就会报 X 重定义
你要养成习惯:
#ifndef __X__
#define __X__
。。。。
。。。。// 你的代码
#endif
util.cpp改成.h,代码前加一句 #pragma once