在C ++中使用类作为其他类的成员数据的问题

时间:2016-05-07 13:36:42

标签: c++ class

我使用的是这个代码:第一个是Rectangle.hpp

#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.我如何使它输出它应该输出的内容?为什么它首先不起作用?

2 个答案:

答案 0 :(得分:0)

从你的代码:

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

so width = 0,Height = 0,因此结果为0

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

答案 1 :(得分: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;

}