C++ 如何将参数多次传递给构造函数

C++ 如何将参数多次传递给构造函数,c++,C++,以下仅给出了第一个参数列表(4,5);第二个(5,8)不起作用。请建议 #include<iostream> #include<string> using namespace std; using std::cout; using std::endl; using std::string; class Rectangle { public: Rectangle(int length, int breadth) { cout << "Area = &

以下仅给出了第一个参数列表(4,5);第二个(5,8)不起作用。请建议

#include<iostream>
#include<string>
using namespace std;
using std::cout;
using std::endl;
using std::string;

class Rectangle
{
public:
Rectangle(int length, int breadth)
{
cout << "Area = " << length * breadth << endl;
}
};

int main()
{
Rectangle rect(4,5); //WORKING
Rectangle rect(5,8); //NOT WORKING
system ("pause");
return 0;
}
#包括
#包括
使用名称空间std;
使用std::cout;
使用std::endl;
使用std::string;
类矩形
{
公众:
矩形(整数长度,整数宽度)
{
cout第二个必须是1

否则,您试图在同一个范围内声明同一个名称的变量不止一次。C++中不允许这样做。交替地,给出第二个<代码> Rect<代码>一个不同的名称,或者使用至少一个范围块

{
    Rectangle rect(4,5);
}
{
    Rectangle rect(5,8);
}

1从技术上讲,这将使用您提供的构造函数和编译器生成的赋值运算符。

当您调用:

Rectangle rect(4,5);
Rectangle rect(5,8);
您正在通过
rect
变量定义一个可访问的
矩形。如果调用:

Rectangle rect(4,5);
Rectangle rect(5,8);
在第一个定义之后,它将抛出一个错误(
rect
已定义)

相反,您必须使用两个不同的变量名:

Rectangle rectA(4,5);
Rectangle rectB(5,8);
不幸的是,在我看来,这不是一个解决问题的聪明方法:为这样的东西填满内存是不好的做法

解决方案1 低内存占用 我不得不说,这不是创建
Rectangle
类的正确方法。我建议将信息存储为私有信息,并使用Sperate方法计算面积:

class Rectangle {

private:
int _length;
int _breadth;

public:
Rectangle (int length, int breadth) {
  _length = length;
  _breadth = breadth;
}

Rectangle (Rectangle old) { //copy old Rectangle
  _length = old._length;
  _breadth = old._breadth;
}

int area () {
  return length * breadth
}

void printArea () {
  cout << "Area = " << area() << endl;
}

};
解决方案2 无内存占用 您可以使用一个简单的函数:

void printArea (int length, int breadth) {
  cout << "Area = " << length*breadth << endl;
}
void打印区域(整数长度、整数宽度){

无法更改变量名?使用类的方式错误。如果只需要计算面积,则应定义一个好的旧C函数或静态方法。