我正在学习c ++中的重载函数,本书中的一个例子是行不通的。这是代码,
#include <iostream>
using namespace std;
//rectangle class declaration
class Rectangle
{
public:
//constructors
Rectangle(int width, int height);
~Rectangle(){}
//overload class function drawShape
void DrawShape() const;
void DrawShape(int aWidth, int aHeight) const;
private:
int itsWidth;
int itsHeight;
};
//constructor implementation
Rectangle::Rectangle(int width, int height)
{
itsWidth;
itsHeight;
}
//overloaded DrawShape - takes no values
//Draws based on current class member values
void Rectangle::DrawShape() const
{
DrawShape(itsWidth, itsHeight);
}
//overloaded DrawShape - takes two values
//Draws shape based on the parameters
void Rectangle::DrawShape(int width, int height) const
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
cout << "*";
}
cout << "\n";
}
}
//Driver program to demonstrate overloaded functions
int main()
{
//Initialize a rectangle to 30, 5
Rectangle theRect(30, 5);
cout << "DrawShape(): \n";
theRect.DrawShape();
cout << "\nDrawShape(40, 2): \n";
theRect.DrawShape(40, 2);
system("pause");
return 0;
}
我遇到的问题是将Rectangle theRect初始化为30,5不输出任何内容,但我知道该函数有效,因为它确实输出了40个矩形。
答案 0 :(得分:2)
你的构造函数没有做任何事情,它应该是
//constructor implementation
Rectangle::Rectangle(int width, int height)
{
itsWidth = width;
itsHeight = height;
}
由于DrawShape
是类Rectangle
中的一个函数,它可能不应该接受任何参数,它应该使用对象的成员变量
void Rectangle::DrawShape() const
{
for (int i = 0; i < itsHeight; i++)
{
for (int j = 0; j < itsWidth; j++)
{
cout << "*";
}
cout << "\n";
}
}
请注意,您的构造函数有一个替代(和arguably preferred)语法,使用member initialization list
//constructor implementation
Rectangle::Rectangle(int width, int height)
: itsWidth{width}, itsHeight{height} {}
答案 1 :(得分:1)
你的构造函数没有初始化任何东西,它应该是这样的:
//constructor implementation
Rectangle::Rectangle(int width, int height)
: itsWidth(width)
, itsHeight(height)
{
}
更改后,您的结果如下所示:
DrawShape():
******************************
******************************
******************************
******************************
******************************
DrawShape(40, 2):
****************************************
****************************************