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).
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.
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);
// ^ ^
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 .
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.