0
60.2 Practice - Sorting By Size (Member Initializers)
You are making a program to store TVs with their width and height. The given program declares a TV class with height and width members, an area() method, as well as a constructor that initializes the members of the class. Complete the program by taking 2 integers as input, create a TV object by passing them to the constructor, and call the area() method. *Note, that the constructor needs 2 integer values. My code is below based on the lesson but it doesn’t work. Please help.
5 Réponses
+ 3
#include <iostream>
using namespace std;
class TV {
public:
TV(int h, int w): height(h), width(w) {};
void area() {
cout <<height*width;
}
private:
int height;
int width;
};
int main() {
//your code goes here
int x, y;
cin >> x >> y;
TV o(x, y);
o.area();
}
+ 2
A few observations:
You need to make 1 TV object.
- You are making 2, 1 called height and another called weight and you're not using either of these objects.
TV requires 2 integers in order to construct one.
- You are passing 1 string to both.
Use cin to get user input if the program requires it.
The member function, area, for the TV takes 0 arguments.
- You are passing 1, the product of 2 non-existing variables.
In order to call a member function you need to tell the code on which object to call it on.
- You are currently treating area as a freestanding function.
area returns void, meaning nothing. So you cannot use it with cout in this case. area already prints it on its own.
Review the tutorial if you need to, these are covered topics.
+ 1
Thanks Dennis for the lengthy explanation. Finally manage to solve it.
0
#include <iostream>
class TV {
public:
TV(int h, int w)
: height(h), width(w)
{
};
void area() {
std::cout<<height*width;
}
private:
int height;
int width;
};
int main() {
//your code goes here
int numH, numW;
std::cin>>numH>>numW;
TV obj = TV(numH, numW);
obj.area();
}
// for any future references https://www.youtube.com/watch?v=wN0x9eZLix4
- 1
#include <iostream>
using namespace std;
class TV {
public:
TV(int h, int w): height(h), width(w) {};
void area() {
cout <<height*width;
}
private:
int height;
int width;
};
int main() {
//your code goes here
TV height("h");
TV weight("w");
cout << area(h*w);
}