初始化值不改变/C++

Initialized values do not change / C++

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

这是我的结果: 这是一个形状。它有 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;
};

例如构造函数的主体

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

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

你应该写

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

还有这个默认构造函数

Shape(){};

不初始化数据成员。

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

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

并且在其他派生的 classes 中你可以覆盖它,例如

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

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

virtual ~Shape() = default;