【发布时间】:2013-05-22 07:38:31
【问题描述】:
我有一些关于使用头文件编码 C++ 程序的问题。
这是我的 header.h 文件:
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length);
double get_perimeter();
double get_area();
void resize(double factor);
private:
double width;
double length;
double area;
double factor;
};
这是我存储所有方法的 Question1.cpp 文件:
#include <iostream>
using namespace std;
class Rectangle
{
public:
Rectangle(double width, double length)
{
width = width; //I have no idea how to use this.something as its in Java
length = length; //Problem probably occurs at here
}
double Rectangle::get_perimeter()
{
return ((width * 2) + (length * 2)) ;
}
double Rectangle::get_area()
{
return (width * length);
}
void Rectangle::resize(double factor)
{
width *= factor;
length *= factor;
}
private:
double width;
double length;
double area;
double factor;
};
最后,这是我的主要方法.cpp:
#include <iostream>
#include "header.h";
using namespace std;
int main()
{
Rectangle rectangle1(2.5,7.0);
cout << rectangle1.get_perimeter();
cout << rectangle1.get_area();
system("PAUSE");
return 0;
}
但是,当我尝试运行该程序时,系统告诉我存在构建错误和未解决的外部问题,我不知道为什么会这样。有人可以帮我解决吗?
提前致谢。
【问题讨论】:
-
你需要在你的questestion cpp文件中包含header.h,你还必须使用this指针:this->width = width;
-
不要在标题中使用
using namespace ...。 -
有什么错误?哪些行导致了错误?你检查过sscce.org 吗?
-
question1.cpp line 5中的矩形类重定义
-
你可以使用
this->width = width。