简体   繁体   中英

Why isn't my class using the values I've given it?

In the process of trying to understand and use classes and methods, I have been trying to create a class with private values that uses a method to alter those values. I create a program that requests input from a user (a length and width) and creates a "rectangle" from those values (it just stores the values they input as if it was a rectangle.) For some reason, the method I used doesn't alter the private length and width values in the class. I used the.h file to create the class and the.cpp to create the function that gets input with the main.cpp being used to call the function. For the sake of simplicity, I removed the input validation section of the code in the.cpp file because it does not affect the class values. Can you help me find my mistake?

My.h file with the class in it:

#pragma once

#include <iostream>
using namespace std;

class Rectangle
{
private:
    double length;
    double width;
public:
    Rectangle()
    {
        length = 0;
        width = 0;
    }
    Rectangle(double a)
    {
        length = a;
        width = a;
    }
    Rectangle(double l, double w)
    {
        length = l;
        width = w;
    }
    void SetLenWid(double l, double w)
    {
    if (l == w)
    {
        Rectangle (l);
        cout << "You have created a square with sides equal to " << length << endl;
    }
    else
    {
        Rectangle (l, w);
        cout << "You have created a rectangle of length = " << length << " and width = " << width << endl;
    }
    }
};

The Rectangle.cpp file:

#include "Rectangle.h"
#include <iostream>



void getInput()
{
    double l, w;
    cout << "Enter the length: ";
    cin >> l;
    cout << "Enter the width ";
    cin >> w;
    Rectangle init;
    init.SetLenWid(l, w);
}

Finally, my main.cpp:

#include "Rectangle.h"
#include "Rectangle.cpp"
#include <iostream>

using namespace std;

int main()
{
    getInput();
    return 0;
}

Sorry for the very long-winded question!

Rectangle(l, w); doesn't do what you think it does. It creates a temporary rectangle, which is then destroyed immedately.

Rectangle(l); also doesn't do what you expect. It's equivalent to Rectangle l; , which creates a rectangle named l using the 0-argument constructor.

You want *this = Rectangle(l, w); , or just assign to the fields directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM