【问题标题】:Initialized values do not change / C++ [closed]初始化值不改变/C++ [关闭]
【发布时间】:2021-05-11 19:34:13
【问题描述】:

我正在制作一个打印形状的点和长度的程序。我在子类的构造函数中初始化了点,在 main 中初始化了长度,但它仍然没有显示我设置的初始化值。

这是我的结果: 这是一个形状。它有 0 个点和长度:1.82804e-322 这是一个形状。它有 1 个点和长度:2.102e-317 这是一个形状。它有 -1 点和长度:2.10154e-317

这是我的代码:

#include <iostream>
#include <math.h>
#include <string>
#define pi 3.14159265358979323846

using namespace std;

class Shape {

private:
    int points;
    double length;
    //constructors
protected:
    Shape(int Spoints, double Slength)
    {
        Spoints = points;
        Slength = length;
    }

public:
    Shape(){};
    //methods
    string getClass() { return "Shape"; }
    void printDetails() { cout << "This is a " << getClass() << ". It has " << points << " points and length: " << length << "\n"; }
    double getlength() { return length; }
};

class Rectangle : public Shape {
    //constructors
public:
    Rectangle(double Slength)
        : Shape(4, Slength)
    {
    }

    //getters
    string getClass() { return "Rectangle"; }
    double getArea() { return (getlength() * 2); };
};

class Triangle : public Shape {
    //constructor
public:
    Triangle(double Slength)
        : Shape(3, Slength){};

    //getters
    string getClass() { return "Triangle"; }
    double getArea() { return ((sqrt(3) / 4) * pow(getlength(), 2)); }
};

class Circle : public Shape {
    //consturctor
public:
    Circle(double Slength)
        : Shape(1, Slength)
    {
    }

    //getters
    string getClass() { return "Circle"; }
    double getArea() { return (pow(getlength(), 2) * pi); }
};

int main()
{
    Shape* s;
    Rectangle r(2);
    Triangle t(3);
    Circle c(4);

    s = &r;
    s->printDetails();
    s = &t;
    s->printDetails();
    s = &c;
    s->printDetails();
    return 0;
};

【问题讨论】:

  • 你的作业倒退了。 Spoints = points; 应该是 points = Spoints;Slength = length; 应该是 length = Slength;。当前版本通过读取未初始化的值导致未定义的行为。
  • 另外,我希望您为每个对象获得"This is a Shape",而不是"This is a Rectangle""This is a Triangle" 等。如果您需要将getClass() 设为virtual 函数希望它表现出多态性。
  • 是的,这是我项目的下一步。我只是想在继续之前找出错误。
  • 您应该将#define pi 更改为const double pi =。宏没有任何类型安全性。

标签: c++ class constructor initialization


【解决方案1】:

例如构造函数的主体

protected: Shape(int Spoints, double Slength){
        Spoints = points; 
        Slength = length;
    }

没有意义,因为您试图重新分配参数而不是类的数据成员。

你应该写

protected: 
    Shape(int Spoints, double Slength) : points( Spoints ), length( Slength )
    {
    }

也是这个默认构造函数

Shape(){};

不初始化数据成员。

还要注意因为函数getClass 不是虚函数没有多态性。你可以像这样声明它

virtual string getClass() const { return "Shape"; }

在其他派生类中,您可以覆盖它,例如

string getClass() const override { return "Rectangle"; }

你还应该将 Shape 类的析构函数设为虚拟

virtual ~Shape() = default;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多