2016-05-07 48 views
0

我使用此代码:首先是Rectangle.hpp问题与使用类在C++其他类的数据成员

#include <iostream> 
//Point 
class point { 
public: 
    void setxy(int nx, int ny); 
    const int getx(); 
    const int gety(); 
private: 
int x; 
int y; 

}; 
void point::setxy(int nx, int ny) { 
x = nx; 
y = ny; 
}; 

const int point::getx() { return x; }; 
const int point::gety() { return y; }; 
//Rectangle 
class rectangle { 
public: 
rectangle(point nLl, point nLr, point nUl, point nUr); 
void getArea(); 
const point getLl() { return Lleft; }; 
const point getLr() { return Lright; }; 
const point getUl() { return Uleft; }; 
const point getUr() { return Uright; }; 
const int getRight() { return Right; }; 
const int getLeft() { return Left; }; 
const int getTop() { return Top; }; 
const int getBottom() { return Bottom; }; 
private: 
point Lleft; 
point Lright; 
point Uleft; 
point Uright; 
int Right; 
int Left; 
int Top; 
int Bottom; 
}; 
void rectangle::getArea() { 
int width = Right - Left; 
int height = Top - Bottom; 
std::cout << "The area is " << width * height << ".\n"; 
}; 
rectangle::rectangle (point nLl, point nLr, point nUl, point nUr) 
{ 

Lleft = nLl; 
Lright = nLr; 
Uleft = nUl; 
Uright = nUr; 
Right = Lright.getx(); 
Left = Lleft.getx(); 
Top = Uleft.gety(); 
Bottom = Lleft.gety(); 
}; 

这是Rectangle.cpp:

#include <iostream> 
#include "rectangle.hpp" 
int main() { 
point nnUleft; 
nnUleft.setxy(0,2); 

point nnUright; 
nnUright.setxy(2,2); 

point nnLright; 
nnLright.setxy(0, 0); 

point nnLleft; 
nnLleft.setxy(0, 2); 

rectangle qd(nnLleft, nnLright, nnUleft, nnUright); 
qd.getArea(); 
char bin; 
std::cin >> bin; 
std::cout << bin; 

} 

我的问题是, ,当编译时,它输出0,当它应该输出4.我怎样才能输出它应该输出的内容?为什么它不在首位工作?

+1

你也有另外一个问题:你的代码是不正确的缩进,正因为如此,几乎是不可读。当代码乱码时,修复错误是两倍。您必须修正您的代码并正确缩进它,以提高找到愿意挖掘它的人的机会,并找出您的代码问题。 –

+0

当然,其中一个点应该是2,0而不是0.2? – user657267

回答

0

从代码:

Left = 0 (nnuLeft.x) 
Right = 0 (nnLright.x) 
Top = 2 (nnULeft.y) 
Bottom = 2 (nnLleft.y) 

所以宽度= 0,身高= 0,这样的结果是0

所以你的左下和右下需要有不同的X值。 同样,您的左上角和左下角需要不同的Y值

+0

我刚刚读到这个之前就想出了这个:-P – TheBeginningProgrammer

0

您的矩形不是真正的矩形。您的形状在main函数中是两行。

如果你想得到一个真正的矩形,修改你的代码。

我修改你的代码是这样的:

#include <iostream> 
#include "rectangle.hpp" 
int main() { 
    point nnUleft; 
    nnUleft.setxy(0, 2); 

    point nnUright; 
    nnUright.setxy(2, 2); 

    point nnLright; 
    nnLright.setxy(2, 0);//here 

    point nnLleft; 
    nnLleft.setxy(0, 0);//and here 

    rectangle qd(nnLleft, nnLright, nnUleft, nnUright); 
    qd.getArea(); 
    char bin; 
    std::cin >> bin; 
    std::cout << bin; 

} 
相关问题