I have started learning C++ recently, doing some simple class/friend function practice, What i was trying to do is, get 2 numbers from user for 2 object of a class by using friend functions only then again using friend function only, multiply those 2 numbers and show on screen. Let's say i typed 2, 3, 4, 5 in order. Expected outputs are 6 and 20, but i can only see 0 and 0 on screen.
#include<iostream>
using namespace std;
class iluvcpp {
int no_1, no_2;
public:
iluvcpp(){}
~iluvcpp(){}
friend void inputno(iluvcpp obj);
friend int multiply(iluvcpp obj);
}multi_1, multi_2;
void inputno(iluvcpp obj) {
cout <<"Enter no 1: ";
cin >> obj.no_1;
cout <<"Enter no 2: ";
cin >> obj.no_2;
}
int multiply(iluvcpp obj) {
return ((obj.no_2)*(obj.no_1));
}
int main() {
inputno(multi_1);
inputno(multi_2);
cout << multiply(multi_1) <<" "<< multiply(multi_2);
cout << endl;
system("pause");
return 0;
}
You pass your objects by value, meaning when you call inputno you're working on a copy. Try changing the function signature to:
void inputno(iluvcpp& obj) {
...
}
Here's an explanation with examples about passing parameters by value vs by reference.
2 suggestions:
A variable/method of a class is private by default. Either make your variables no_1 and no_2 public as well, or write a setter, if you're familiar with it. To have them public by default, use struct, as opposed to class.
As others already have pointed out, you're not modifying multi_1 and multi_2 directly. Either have them passed in by reference (The answer of orip mentions exactly that), or make them return this iluvcpp obj Object and call them like:
multi_1 = inputno(multi_1);
void inputno(iluvcpp obj) has one parameter named obj and no return value. That's the wrong way around here, inputno doesn't need anything from main but it should return something:
iluvcpp inputno(void) { ... or (equivalent) iluvcpp inputno() { ....
You'll need a return something; statement at the end, so C++ knows what value to return from inputno.
Related
This question already has answers here:
How to set cin to a member function of a class in C++?
(3 answers)
Closed 2 years ago.
This is my first time using classes and I'm writing a simple program that will take a certain roman numeral and print out the numerical equivalent. However, I'm struggling to code my user input, my cin >> romanObject.getRomanNumeral(); isn't working. I get error E0349 saying no operator ">>" matches these operands. However, when I used just a simple char variable declared in my main function instead it worked fine. Why doesn't my variable in my class work?
#include <iostream>
#include <string>
using namespace std;
class romanType {
public:
void setRomanNumeral(string x) {
romanNumeral = x;
}
string getRomanNumeral() {
return romanNumeral;
}
private:
string romanNumeral;
};
void store();
int main()
{
store();
return 0;
}
void store() // Takes user input.
{
romanType romanObject;
romanObject.setRomanNumeral("Blank");
cout << "Enter one of the following roman numerals" << endl;
cout << "I, V, X, L, C, D, M." << endl;
cin >> romanObject.getRomanNumeral();
}
Why doesn't my variable in my class work?
It works just fine, except that you're not returning it. When you are returning something by value, you are essentially making a temporary copy of the variable. Of course, you can return it by reference:
string &getRomanNumeral() {
return romanNumeral;
}
However, that doesn't really make much sense, since you no longer need setRomanNumberal(), you can simply use getRomanNumberal():
romanObject.getRomanNumeral()="hello world";
The detail that you missed that setting the value of your class member is a part of initializing it by reading its value from std::cin. After you read the string, what do you need to do? You need to set it, so why do you want to use something called getRomanNumeral()? That doesn't make much sense, doesn't that?
So, really, your original approach was the correct one, something along the lines of:
string s;
cin >> s;
romanObject.setRomanNumeral(s);
You're getting the variable, from cin, and you're setting it in your object; you're not getting the existing value of this variable in your object, at any point.
So my program is intended to accept input from the user to create an object with several attributes(variables) and those objects are put into vector. I'm having a particular issue with being able to change the quantity of a particular item in question. It remains unchanged regardless of how many times I call the function from main.cpp.
class ClassA {
public:
void SetQuantity(int quantityToGet);
...
private:
int itemQuantity;
...
};
void ClassA::SetQuantity(int quantityToGet) {
itemQuantity = quantityToGet;
}
class ClassB {
public:
ClassB();
void UpdateItemQnty();
int FindItemLoc(string targetItem);
...
private:
vector<ClassB> itemsInVector;
...
};
void ClassB::UpdateItemQnty() {
ClassA currItem;
string targetName;
int newQuantity;
int itemLoc = -1;
cout << "Enter the item name: ";
getline(cin, targetName);
itemLoc = FindItemLoc(targetName);
cout << "Enter the new quantity: ";
cin >> newQuantity;
cin.ignore();
if (itemLoc > -1) {
currItem = itemsInVector.at(itemLoc);
currItem.SetQuantity(newQuantity); // FIXME (???)
}
else {
cout << "Item not found in vector. Nothing modified." << endl;
}
}
I'm not getting any errors and the functions I didn't mention or show definition/declarations for, all work properly. I think I need to use a pointer, but I'm not sure how.
I'll likely delete this after I receive an answer based on the response
Thank You
I can see two strange things in your code:
Your are assigning a ClassA object with ClassB object (above the call of setQuantity). That should give an error, but I guess you made a typo in your post...
when retrieving the data from the list, your are copying it to the local variable currItem! Hence you are only changing a local copy, not the data in the list.
Declaring currItem as a reference would do the trick in this case, but the declaration of a reference object requires an assignment:
ClassA &currItem = itemsInVector.at(itemLoc);
currItem.SetQuantity(newQuantity);
You're simply setting the temporary variable's value. Try this,
itemsInVector[itemLoc].SetQuantity(newQuantity);
For th following code:
#include <iostream>
class Test
{
public:
int i;
void get();
};
void Test::get()
{
std::cout << "Enter the value of i: ";
std::cin >> i; // Line 1
}
Test t;
int main()
{
Test t;
t.get();
std::cout << "value of i in local t: "<<t.i<<'\n';
::t.get();
std::cout << "value of i in global t: "<<::t.i<<'\n';
return 0;
}
Though I know what is happening in the above code i.e. the values are assigned to the local and global t , I am confused by the line 1 as I am unable to understand how the value received from the user by the line 1 is getting assigned to the t.i or ::t.i .
It would be much appreciated If someone can help me explain **behind the scene of above problem **.
Test::get() is a member function.
Inside a member function, you can name any member variable of that class, and it'll affect the object you called the function on.
Read the chapter in your C++ book about classes.
Scenario
I am in the process of learning C++, so please forgive my naivety. I have attempted to build my own class, objects and methods - each of which seem to work as expected. However I am running into issues with what seems to be uninitialized storage (and possibly the use of local objects?) however I would like to know how to fix it, if indeed it is meant to be, or an alternative. My current train of thought is that the object needs to be passed...however that could be way off...
Code
//header
class Car{
public:
USHORT GetMin();
void SetMin(USHORT min);
private:
USHORT itsMinPrice;
};
USHORT Car::GetMin(){
return itsMinPrice;
}
void Car::SetMin(USHORT min){
itsMinPrice = min;
}
-
void StartingPrices(){
Car Mercedes;
std::cout << Mercedes.GetMin() << "\n";
Mercedes.SetMin(50);
std::cout << Mercedes.GetMin()<< "\n";
}
int main(){
float input;
Car Mercedes;
Mercedes.SetMin(100);
StartingPrices();
std::cout << Mercedes.GetMin() << "\n";
std::cin >> input;
return 0;
}
Expected output
100, 50, 50
Actual output
debug win32 - 52428, 50, 100
release win32 - 0, 50, 100
In your StartingPrices function, the Mercedes object you call GetMin is created on the line before, i.e., not the same object as the one you create in the main function.
That means that the object do not yet have itsMinPrice set to anything, hence the value will be garbage (that is, a value which you don't really have control over), in this case 52428 in debug and 0 in release.
What I think you wish to do is pass a reference of the Mercedes object from the main function into the StartingPrices function:
void StartingPrices(Car& mercedes){
std::cout << Mercedes.GetMin() << "\n"; // Here the GetMin method will return 100.
...
}
int main(){
....
Car Mercedes;
Mercedes.SetMin(100);
StartingPrices(Mercedes);
....
}
Its also a good idea to set the default value of the members in the constructor of the class.
In your Car class you do not initialize your member variable itsMinPrice except when you call SetMin, this means there is a risk that you will use an uninitialized Car instance if you forget to call SetMin on it. Normally it is good to have initialization in a constructor of the class with some value e.g.
Car() : itsMinPrice(0) {
}
or create a constructor that takes an initial value
Car(USHORT minValue) : itsMinPrice(minValue) {
}
I want to output the values of the private class members Bankcode and AgentName. How can I do this from within my main() function, or in general, outside of the BOURNE class.
My initial code attempts are below:
#include <iostream>
#include <string>
using namespace std;
class BOURNE
{
string Bankcode ={"THE SECRET CODE IS 00071712014"} ; /*private by default*/
string AgentName={"Jason Bourne"}; /*private by default*/
public:
void tryToGetSecretCodeandName(string theName ,string theCode); //trying to get the private
void trytoGetAgentName( string name); // try to get name
};
//***********************defining member function**************************************
void BOURNE::tryToGetSecretCodeandName(string theName, string theCode) //member defining function
{
Bankcode=theCode; //equalling name to the code here
AgentName=theName; //the samething here
cout<<theCode<<"\n"<<theName; //printing out the values
}
//************************main function*****************************
int main()
{
BOURNE justAnyObject; //making an object to the class
justAnyObject.tryToGetSecretCodeandName();
return 0;
}
Third Answer
Your code has two 'getter' style functions, but neither one takes no arguments. That is, both of your functions require arguments to be passed.
Your main function is calling get...CodeandName(), which has no arguments. As such, you get a compiler error, probably complaining about valid signatures, or arguments passed.
Edited Answer
If you only want to get the values, the typical (as far as I am aware) implementation is something like
std::string BOURNE::getCode()
{
return Bankcode;
}
std::string BOURNE::getName()
{
return AgentName;
}
int main()
{
BOURNE myAgent;
cout<< "The agent's name is : " << myAgent.getName() << endl;
cout<< "The agent's code is : " << myAgent.getCode() << endl;
}
Original Answer, left in because I feel like it's more useful
I suspect what you're asking is if you could do something like
void BOURNE::tryToGetSecretCodeandName(string theName, string theCode)
{
if (Bankcode == theCode) {
cout<< "You correctly guessed the code : " << Bankcode << endl;
}
if (AgentName == theName) {
cout << "You correctly guessed the agent's name : " << AgentName << endl;
}
}
This will allow you to repeatedly guess at the name, and get output when you're correct.
If you wanted to disable this kind of guessing, then you could consider creating a new class (possibly derived from/based on std::string - but see this question for reasons to be careful!) and implement an operator== function which always returned false.