初始化值不改变/C++

时间:2021-05-11 19:34:13

标签: c++ class constructor initialization

我正在制作一个程序来打印形状的点数和长度。我在子类的构造函数中初始化了点,在 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;
};

1 个答案:

答案 0 :(得分:3)

例如构造函数的主体

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;