gpt4 book ai didi

C++ 指针或 header 问题

转载 作者:行者123 更新时间:2023-11-30 02:31:57 25 4
gpt4 key购买 nike

我有一个示例程序,其主 cpp 文件有

    Rectangle rect(5, 5);
Triangle tri(5, 5);
Shape *rectangle1 = ▭
Shape *triangle1 = &tri;
rectangle1->setValues(3, 3);
triangle1->setValues(3, 3);
int area = rectangle1->getArea();

std::cout << area << std::endl;
area = triangle1->getArea();
std::cout << area << std::endl;

std::cin.get();

return 0;
}

矩形、三角形、形状的头文件如下:

矩形.h

#ifndef RECTANGLE_H
#define RECTANGLE_H

#include "Shape.h"

class Rectangle: public Shape {
public :
int length;
int width;
Rectangle(int length, int width);
int getArea();
//Rectangle::~Rectangle(void);
};
#endif

三角形.h

#ifndef TRIANGLE_H
#define TRIANGLE_H

#include "Shape.h"

class Triangle: public Shape {
public :
int length;
int width;
Triangle(int length, int width);
int getArea();
//Triangle::~Triangle(void);
};

#endif

形状.h

#ifndef STDAFX_H
#define STDAFX_H
#ifndef SHAPE_H
#define SHAPE_H
#include <iostream>

class Shape
{
protected:
int width;
int length;
public:
Shape(int length, int width);
void setValues(int length, int width);
virtual int getArea() = 0;
};

#endif
#endif

shape、矩形、三角形的cpp文件如下:

矩形.cpp

#include "stdafx.h"
#include "Rectangle.h"
Rectangle::Rectangle(int length, int width): length(length), width(width), Shape(length, width)
{
}
int Rectangle::getArea() {
return length * width;
}

三角形.cpp

#include "stdafx.h"
#include "Triangle.h"
Triangle::Triangle(int length, int width): length(length), width(width), Shape(length, width)
{
}
int Triangle::getArea()
{
return length/2 * width;
}

形状.cpp

#include "stdafx.h"
#include "Shape.h"
#include <iostream>

Shape::Shape(int length, int width): length(length), width(width) {

}

void Shape::setValues(int length, int width) {
this->length = length;
this->width = width;
}

我的思路是,因为三角形和矩形继承自 Shape,并且我将 rectangle1 设置为指向矩形对象,将 triangle1 设置为指向三角形对象,一旦使用默认构造函数值创建了 2 个形状,我将调用 setValue ()(它应该适用于从 Shape 继承的所有对象。这应该将每个形状的长度和宽度值更改为 3、3,并且当我为每个形状实例运行 getArea 时,矩形应该返回 3*3,三角形应该返回 3 *1.5. 但是,它们都返回我调用 setValues 之前的原始区域(25 和 10)。

我对我的指针或头文件有什么不理解的地方吗?

谢谢!

最佳答案

问题是您在 child 类中有单独的 widthlength 成员变量。因此子类中的 getArea 函数将使用这些变量而不是基类中的变量。

关于C++ 指针或 header 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36964512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com