2010-07-23 3 views
2

Привет всем Я очень новичок в C++ и могу быть в моей голове по этой проблеме, которую я пытаюсь решить. Хорошее визуальное объяснение и решение моих ошибок или даже лучший исправленный исходный код - это все, о чем я прошу. Спасибо всем, кто вкладывает туда интерес в мой вопрос.Rectangle class

Существует проблема: Создайте класс с именем rectangle, чтобы представлять прямоугольник. Класс должен содержать:

  • Два двойных поля данных с шириной и высотой, которые определяют ширину и высоту прямоугольника. не
  • нет-Arg конструктор, который создает прямоугольник по умолчанию с шириной 1 и высотой 1.
  • конструктор, который создает прямоугольник с заданной ширины и высоты
  • Аксессор и Mutator функции для всех полей данных
  • Функция с именем get Area() возвращает область этого прямоугольника.
  • Функция с именем getPerimeter(), которая возвращает перемещающего.

Нарисуйте диаграмму UML для класса. Внедрить класс. Напишите тестовый прогон, который создает два прямоугольных объекта obejects. Назначьте ширину 4 и высоту 40 для первого объекта и ширину 3,5 и высоту 35,9 ко второму. Отобразите свойства обоих объектов и найдите их области и периметры.

Вот что я до сих пор:

#include <iostream> 
using namespace std; 

class Rectangle 
{  
public:  
    double height; 

public: 
    double width; 
    Rectangle() 
    { 
     width = 4;   
    } 

    rectangle(double newArea) 

    double height; 
    height() 
    (
     height = 40 
     { 
      { 
      area = height* width; 
      } 


    double getArea() 
    { 
    return Area; 
    } 

    bool isOn() 
    { 
    return on; 
    } 


    double getPerimeter() 
    { 
    return Perimeter; 
    } 

    void setPerimeter(double radius) 

    cout << "The area of the Rectangle" 
<< rectangle1.area<<"is"<<rectangle1.getArea()<< endl; 
cout<<"The area of the Rectangle" 
<<rectangle.area2.area<<"is"<<rectangle2.getArea()<<endl; 


    return 0; 
} 
+0

Если вы добавили 4 пробела перед кодом, он будет отформатирован как код. Я подозреваю, что у вас есть другие проблемы (посмотрите код, начинающийся с 'rectangle (double newArea)'). Также что с функцией 'setPerimeter'? В прошлый раз, когда я проверил, прямоугольники не имеют радиуса (и определения функций заканчиваются либо символом '{/ * здесь идет * /}', либо ';') –

+1

Вы также должны объяснить, что не работает, когда вы отправляете вопрос. Разве это не компиляция? Не работает ли какая-то его часть? Можете ли вы не думать о том, как сделать одну часть? –

+0

Это третья проблема, которую я видел у вас сегодня, которая состоит из заданий на домашнюю работу и некоторого кода, не очень отформатированного, и никаких указаний на то, что вы на самом деле находите неправильно.Не могли бы вы проверить, что опубликовано, что вы написали, и рассказать нам, что на самом деле неправильно? –

ответ

1

Шаг 1: Удалите весь код, который не в спецификации:

class Rectangle { 

private: 
    double height; 
    double width; 

public: 
    Rectangle() { 
     // fill in code here 
    } 

    Rectangle(double width, double height) { 
     // fill in code here 
    } 

    double getArea() { 
     // fill in code here 
    } 

    double getPerimeter() { 
     // fill in code here 
    } 

    double getWidth() { 
     // fill in code here 
    } 

    void setWidth(double newWidth) { 
     // fill in code here 
    } 

    double getHeight() { 
     // fill in code here 
    } 

    void setHeight(double newHeight) { 
     // fill in code here 
    } 

}; 

Остальная часть кода просто делает это более сложным , Вам не нужна переменная области или периметра, и конструктор, принимающий область в качестве аргумента, не имеет смысла (вы, кажется, рассматриваете свой прямоугольник как круг).

6

Если вы хотите узнать, что происходит здесь, проверить это

#include <iostream> 
using namespace std; 

class Rectangle{ 
private:  // In nearly all cases you want to keep your member variables private 
    double height; // This allows you to be certain of how they are accessed. 
    double width;  // This provides a level of security to the class. 

public:   // Only need one public: 
    // Constructors are called when you define a new variable of type Rectangle 
    Rectangle()  // No arguments means this constructor takes no extra input when called. 
    { 
    width = 1.0;  // Sets width and height to 1 
    height = 1.0; 
    } 
    Rectangle(double a_width, double a_height) { // Constructor needs exact(case-sensitive) match of class-name 
    /* Set width and hieght to the arguments passed into the constructor in here.*/   
    } 
    // Accessor/Mutator methods are more easily called get/set methods. 
    double getHeight(){ // Get height called on rectangle class 
    return height;  // Returns the value of the class member "height" 
    } 

    /*Make a method to get the width here.*/ 

    // In c++ you can return the results of equations directly 
    // i.e. 
    // int x = 2; 
    // return x*x; // returns 4 
    // Try something simliar for getArea() and getPerimeter(); 

    double getArea() const 
    { 
     return /*area equation goes here*/ ; 
    } 
    double getPerimeter() const 
    {      
    return /*perimeter equation goes here*/; 
    } 
} 
    // You should split these displaying statements into the main function, 
    // Which is what you meant to do, right? ;) 
    int main(){ 
    // In order to use your new class, you need to declare a variable of its type 
     Rectangle rectangle1;  
     // When you declare a new variable without any arguments its default constructor is called. 
     // This means that the rectangle class decides to use the height = 1; width = 1; constructor from above. 
     // You can check this using your getHeight() and getWidth(), when you implement them. 

     cout << "The area of the Rectangle is" << rectangle1.getArea() << endl; 

    return 0; 
} 

Ах напоминает мне о Тейнг CSCI1100

+0

+1 очень хороший ответ –

+1

Я боюсь, что мои усилия напрасны. – James

+0

'' Конструкторы вызываются при переменных __define__. Объявление не вызывает вызов ctor. См. Здесь: http://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration/1410632#1410632 – sbi

2

Вот рабочий раствор,

Исходный код:

#include <iostream> 

using namespace std; 

class Rectangle { 
    private: 
     double width; 
     double height; 
    public: 
     Rectangle(double w=1, double h=1); 

     double getWidth(); 
     void setWidth(double w); 

     double getHeight(); 
     void setHeight(double h); 

     double getArea(); 
     double getPerimeter(); 
}; 

Rectangle::Rectangle(double w, double h):width(w),height(h) {} 

double Rectangle::getWidth() { return width; } 

void Rectangle::setWidth(double w) {width = w; } 

double Rectangle::getHeight() { return height; } 

void Rectangle::setHeight(double h) { height = h; } 

double Rectangle::getArea() { return width*height; } 

double Rectangle::getPerimeter() { return 2*(width+height); } 

int main() 
{ 
    Rectangle r1(4,40); 
    Rectangle r2(3.5,35.9); 

    cout << "Rectangle #1 :: width[" << r1.getWidth() << "] height[" << r1.getHeight() << "] area[" << r1.getArea() << "] perimeter[" << r1.getPerimeter() << "]" << endl; 
    cout << "Rectangle #2 :: width[" << r2.getWidth() << "] height[" << r2.getHeight() << "] area[" << r2.getArea() << "] perimeter[" << r2.getPerimeter() << "]" << endl; 
} 

Выход:

Rectangle #1 :: width[4] height[40] area[160] perimeter[88] 
Rectangle #2 :: width[3.5] height[35.9] area[125.65] perimeter[78.8] 
+0

'-1' от меня для размещения ответного ответа на вопрос« домашнее задание ». – sbi

+1

@sbi: +1 для аннулирования -1 – bragboy

1
//This Is The Complete Program A Run This 10 Time on VC++ For More check 
//For More Code and Information and News www.exploretomorrow.blogspot.com 
#include <iostream> 
using namespace std; 
class Rectangle // Class Rectangle 
{ 
public: 
    Rectangle(float L, float W); // Constructor 
    float getLength(){return length;} 
    void setLength(float L); 
    float getWidth(){return width;} 
    void setWidth(float W); 
    double perimeter(void){return (length*2 + width*2);} // Perimeter function 
    double area(void) {return (length*width);} // Area funcion 

private: 
    float L, W, length, width; 
     }; // End of class Rectangle 

Rectangle::Rectangle(float L, float W) // Scope function 
{ 
length=L; 
width=W; 
} 

void Rectangle::setWidth(float W)//I'd like to change this to a do/ while loop?? 
{ 
if ((W < 0.0) || (W > 20.0)) 
    { 
     width = 1.0; 
    } 
    else 
     { 
      width = W; 
     } 
    return; 


} 
float getWidth() 
{ 
    return W;//Is this right? 
} 

void Rectangle::setLength(float L)//same here-do/while loop? 
{ 
if ((L < 0.0) || (L > 20.0)) 
    { 
     length = 1.0; 
    } 
    else 
     { 
      length = L; 
     } 
    return; 
} 
float getLength() 
{ 
    return L; 
} 

void Rectangle::get(float L, float W) 
{ 



} 
double Rectangle:perimeter(float L, float W) 
{ 
perimeter = (2*L) + (2*W); 
cout << "The perimeter of the rectangle is: " << perimeter << endl; 
} 

double Rectangle::area(float L, float W) 
{ 
area = L*W; 
cout << "The area of the rectangle is : " << area << endl; 
} 

int main() // main() I'm sure something is wrong here. 
// I understand the main function, but when I use classes I get confused... 
{ 
rectangle MyRectangle; 
cout << "Please enter the length of the rectangle: " << endl; 
cin >> MyRectangle.getlength >> endl; 
cout << "Please enter the width of the rectangle: " << endl; 
cin >> MyRectangle.getwidth >> endl; 


return 0; 
} // End of main()