【发布时间】: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