Im having unclear image of pointers and char passing with functions. please anyone can tell me where im doing wrong and brief idea about pointers?ex : where should i use them, etc...
#include <iostream>
using namespace std;
class book{
private:
char *CName;
int CFee;
int NoPeople;
int Income;
public:
void setData(char &x,int y,int z){
CName = &x;
CFee = y;
NoPeople = z;
}
void calIncome(){
Income = CFee * NoPeople;
}
void viewIncome(){
cout<<Income;
cout<<CName;
}
};
int main(){
book b1;
b1.setData('DISE',20000,30);
b1.calIncome();
b1.viewIncome();
}
im getting error in this code
//b1.setData('DISE',20000,30); "non-const lvalue reference to type 'char' cannot bind to a temparory of type 'int'"
In your code there is no need for pointers. You should use std::string:
#include <string>
...
string CName
...
void setData(const string& x,int y,int z){
CName = x;
and in setData call you should use double quotes (which are for strings) instead of single quotes (which are for individual characters).
You should change setData() declaration to void setData(const char *x,int y,int z)
As you're currently doing you are expecting a reference to a single char as parameter, which cannot be used to assign a char* pointer that is meant to point at a character array.
Also you aren't specifying a character array literal in the call:
b1.setData('DISE',20000,30);
Needs to be changed to
b1.setData("DISE",20000,30);
// ^ ^
b1.setData('DISE',20000,30);
char is only one char, like 'D', if you have multiple char, that is string, and you need to pass it as "DISE"
With your method signature, void setData(char &x,int y,int z) you can only pass char. That is one character.
setData metod is completely useless here. Its work should be done by a constructor, and the name variable (which should NOT be named CName should be an std::string. viewIncome should automatically call calIncome and a dirty flag should probably be introduced. Otherwise calIncome should be a free/static function and the income member should be removed. The function parameters should also be reasonably captioned.
And I'll even answer the question:
class Book {
std::string name;
int fee;
int noPeople;
int income;
public:
Book(std::string name, int fee, int noPeople) :
name(std::move(name)),
fee(fee),
noPeople(noPeople)
{
}
void calIncome() {
income = fee * noPeople;
}
void viewIncome() {
calIncome();
std:: cout << income << name;
}
};
int main() {
Book b1 ("DISE", 20000, 30);
b1.viewIncome();
}
See it live on Coliru.
Related
This might be a stupid simple thing I'm overlooking, but I am setting values in the Data::Data(char *DataType...) function as they are being passed in, and as I hover over them, they are setting fine (the variables type, material, ID, unit, reading when hovered over are what they should be).
However, when the getData function is called below, when I hover over the pointer arguments(*type, *materials.. etc) they are set to random strings like directory names and file names. I'm not sure why this is happening, because when the variables are being set above they are right.
I've included the header and implementation files for the Data class, where all of these functions are defined, but If I need include where they are being called please let me know, the only reason I didn't is because the calls are short and files are filled with other irrelevant stuff. Thanks
Data.cpp
#include "Data.hpp"
Sensor::Sensor(char *DataType, char *Material, int ID, char *Sensor, double Min, double Max) {
strcpy(type, Type);
strcpy(material, Material);
ID = SIDs;
strcpy(unit, Units);
max = Maxs;
min = Mins;
}
Sensor::Sensor() {}
double Data::generateData() {
reading = min + (rand() % (int)(max - min + 1));
return reading;
}
void Data::getData(char *type, char *material, int *ID, char *unit, double *reading) {
return;
}
Data::~Data(){}
Data.hpp
#ifndef Data_hpp
#define Data_hpp
#include
#include
#include
using namespace std;
class Data
{
public:
Data();
Data(char *Type, char *Material, int ID, char *Unit, double Min, double Max);
~Data();
void getData(char *type, char *material, int *ID, char *unit, double *reading);
private:
char type[32];
char material[32];
int ID;
int reading;
char unit[32];
double min;
double max;
double generateData();
};
#endif
Your implementation of Sensor::getData does not do what you think it does.
Let's look at this class:
class Foo
{
void getX(int* x)
{
}
int* x;
};
Within getX, the parameter x hides the member x of the same name. This function does literally nothing: A user passes a pointer to an int, which gets the name x in this function. The member is not automatically copied into there (which would be surprising, since you could name the parameter anything else). If you want to do that, you must do it explicitly:
void getX(int* x)
{
*x = *this->x; // Pointed-to value is copied
//x = this->x; // Pointer is copied
}
If you do not set the function parameter to anything, the pointer will keep pointing to random garbage in memory, which is what you are seeing in your debugger.
The more common way to denote "this parameter will be changed/set by this function" is passing a reference:
class Foo
{
void get(char*& x, int*& y, double& z)
{
x = this->x; // Now both parameter and member point to the same location.
y = this->y; // Now both parameter and member point to the same location.
z = this->z;
}
char x[32];
int* y;
double z;
};
Or, if you don't want to copy the pointers but the pointed-to values:
void get(char* x, int* y, double& z)
{
strcopy(x, this->x);
*y = *this->y;
z = this->z;
}
(PS: I recommend using std::string instead of char arrays if your use case allows for it.)
You uninitialized arguments are set to random garbage no matter if you call getData() or not. Try to print them out without calling getData() and see.
This question already has answers here:
Returning multiple values from a C++ function
(23 answers)
Closed 7 years ago.
The definition is only returning the y param, I am just learning function prototype
#include <iostream>
using namespace std;
int doDateofBirth(int m , int d , int y);
int main(){
cout << "My DoB is, " << doDateofBirth(4,14,1998) << endl;
}
int doDateofBirth(int m,int d,int y){
return m,d,y;
}
You can't return multiple objects in C++.
return m,d,y;
That uses the comma operator, which evaluates its left-hand-side expression, throws away its value, then returns the value of the right-hand-side expression. In this case, it's the same as if you had written
return y;
You could make a class to represent a date, then return that:
struct Date {
//maybe add protection, constructors, methods, etc
int month;
int day;
int year;
};
Date doDateOfBirth (const Date& something);
To return as many as you like use : boost::tuple for C++ 11 and newer
http://theboostcpplibraries.com/boost.tuple
In C++, if you want to return multiple variables, consider one of these options:
Group those variables that you want to return into a struct or a class, depends on how big your object is, and use the struct/class as an parameter inside your program
Use reference parameters
Based on your example, you could use reference variable option:
Prototype
void doDateofBirth(int &m , int &d , &int y);
Implementation:
void doDateofBirth(int &m,int &d,int &y){
// do your coding here
}
This is how you call the function:
int month, day, year;
doDateOfBirth(month, day, year);
Usually when you feel the need to return multiple values, those values actually represent a bigger whole, which you should represent with a distinct datatype containing those values. E.g.:
struct DateOfBirth
{
const int month;
const int day;
const int year;
};
DateOfBirth doDateofBirth(int m, int d, int y){
return { m, d, y };
}
And doDateofBirth behaves exactly like a constructor here, so we'll make it a constructor:
struct DateOfBirth
{
DateOfBirth(int m, int d, int y) : month(m), day(d), year(y) { } // constructor
const int month;
const int day;
const int year;
};
Which can then be used like this:
int main()
{
DateOfBirth mybd(666, 42, 69);
printf("%d/%d/%d\n", mybd.year, mybd.month, mybd.day);
}
I am a real c++ beginner and I have a problem with my char array output in a c++ excerise. I was asked to transform a certain UML class in to c++ and generate an working output with the parameters given in main. Here ist the code:
#include <iostream>
#include <stdlib.h>
/*My class defintion book*/
class Book
{ protected:
long int number;
char author[25];
int year;
bool lent;
void setLent(bool x);
bool getLent();
public:
Book(long int n, char a[25], int j, bool x);
long int getNr();
int getYear();
void print();
};
/*Method definition Book*/
Book::Book(long int n, char a[25], int j, bool x)
{number=n;
author=a;
year=j;
lent=x;}
long int Book::getNr()
{return number; }
int Book::getYear()
{return year;}
void Book::setLent(bool x)
{lent=x;}
bool Book::getLent()
{return lent;}
void Book::print()
{
std::cout << "Book Nr: " << number << std::endl;
std::cout << "Author: " << author << std::endl;
std::cout << "Year: " << year << std::endl;
if (lent==0)
std::cout << "Lent [yes/no]: no" << std::endl;
else
std::cout << "Lent [yes/no]: yes" << std::endl;
}
/*MAIN*/
int main()
{
Book b1(123456, "test", 2014, false);
b1.print();
system("pause");
return 0;
This is my output:
Book Nr: 123456
Author: b<Vv-[[vóYA
Year: 2014
Lent [yes/no]: no
Press any key to continue...
As you can see all outputs work except for the "Author". There I am getting crap. Note that I have to use char as type. since it is given in the UML class I had to transform into c++.
I really searched everywhere. But didn't find the correct solution. I have the feeling it will be a very simple one...
Thanks in advance for your help!
The reason this doesn't work is that you're assigning your pointer author to another pointer a, which then goes out of scope... so you're left with author pointing to some garbage. If you want to stick with character arrays, you'll have to copy all the data that a points to:
strcpy(author, a);
But since it's C++, you should just use strings, which are easier to deal with:
class Book {
...
std::string author;
....
};
Book::Book(long int n, const std::string& a, int j, bool x)
: author(a), ...
{ }
You are printing out uninitialized data.
Make author a string
#include <string>
class Book
{ protected:
long int number;
std::string author;
int year;
bool lent;
and make the argument to the constructor a string as well
Book::Book(long int n, const std::string& a, int j, bool x)
Arrays of characters are not as flexible as std::strings. they are just chunks of data. If you want to use strings then use std::string instead.
Also, use an initializer list in C++ constructors, not java style
Book::Book(long int n, const std::string &a, int j, bool x)
: number(n),
author(a),
year(j),
lent(x)
{ }
There are two bugs in your code:
Book::Book(long int n, const char a[25], int j, bool x)
{
number=n;
strncpy(author, a, 25); // author = a; doesn't work! shouldn't compile either...
year=j;
lent=x;
}
First: The variable author is a pointer to a zero terminated string. You can use strcpy() to copy this string. Therefore you need to #include <memory.h. But you need to be sure that the string -is- really zero-terminated and fits into your target variable! Else you'll overwrite other memory regions next to the target variable, which is also called a buffer overflow! Better use strncpy(target, source, maxlength); which avoids this problem.
Second: Your parameter a should be "const" as you want to be able to call it with a string constant like in Book b1(123456, "test", 2014, false); where "test" is a constant!
As others already suggested you should use std::string instead of a[25]. C-Strings are "C" and not "C++" and you should try to avoid them. C-Strings can introduce a lot of bugs into your code and enable buffer overflows (=security problems), too. Also they are more complicated to handle. You need to #include <string> to use them.
i have a class
class Studentas
{
public:
static const int CPaz=10;
private:
string pavarde, vardas, grupe;
double paz[CPaz], // paþymiø masyvas
np; // paþymiø kiekis
double vidurkis;
double STsk;
public:
Studentas(): pavarde(""), vardas(""), grupe(""), np(0), STsk(1),vidurkis(0)
{ }
double imtinp(){return np;}
double imtipaz(int i){return paz[i];}
void Deti(string pav, string vard, string grup, int np, int pz[],double vid);
void grupeDETI(string grp,double vidurk){grupe=grp;vidurkis+=vidurk;}
double iv(){return vidurkis;} <---------------------------------------THE ONES IM USING
void isvestiVID(){vidurkis/=STsk;}
void pridetiSK(){STsk++;}
string ig(){return grupe;} <---------------------------------------THE ONES IM USING
string Spausdinti(int i);
string SpausdintiGrupes();
};
the bool i was using bool
myfunction(Studentas const &d1,Studentas const &d2){return (d1.iv() > d2.iv() || d1.iv()==d2.iv() && d1.ig() < d2.ig());}
vector<Studentas> grupe;(with whatever length)
sort(grupe.begin(), grupe.end(),myfunction);
and i get an error, " cannot convert 'this' pointer from 'const Studentas' to 'Studentas &' "
EDIT : i use void functions to get my variables.
EDIT2: thanks for all the help, i think i'll just bubble this one out.Dont have the time to waste, thanks again for the help.
EDIT3: dun goofed on my operator overlays, the method below works.
Mark your methods as const:
double iv() const {return vidurkis;}
This way you'll be able to call them on const objects, which is what d1 and d2 are.
All methods that logically don't need to modify the object should be marked const.
My program simply is to increase the salary int the emp class throw the the function increase
but I'm having this error int the call function line from the line :
No suitable constructor to convert from int to emp
here 's my code :
#include <iostream>
#include <string>
using namespace std;
class emp
{
public:
int salary;
};
void increase(emp x,emp y)
{
x.salary+=100;
y.salary+=250;
}
int main()
{
int value=0;
emp fst, scnd;
cin >> fst.salary >> scnd.salary;
increase(fst.salary,scnd.salary);
cout << fst.salary << endl << scnd.salary << endl;
cin >> value;
return 0;
}
increase expects two emps as parameters, yet you pass in two ints.
Change
increase(fst.salary,scnd.salary);
to
increase(fst,scnd);
Your next question is going to be why the values don't change, so to save you the trouble - it's because you're passing by value, effectively changing copies of your original objects. You'll need to pass by reference:
void increase(emp& x,emp& y)
increase(fst.salary,scnd.salary); should be increase(fst,scnd);, void increase(emp x,emp y) ... should be void increase(emp& x,emp& y) ...
You need to pass emp not int. Further, you are passing parameters by value. Use this instead:
void increase(emp &x,emp &y)
And pass the struct variables; i.e. fst and scnd instead of fst.salary and scnd.salary. Refer this question for better understanding.