This line canot pass under VS Studio, But it is running under CodeBlocks.
cg1.RegisterGoods("c++", 23, 32);
'void CGoods::RegisterGoods(char [],int,float)': cannot convert argument 1 from 'const char [4]' to 'char []'
like so:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <cstring>
using namespace std;
class CGoods
{
private:
char Name[21];
int Amount;
float Price;
float Total_value;
public:
void RegisterGoods(char name[], int amount, float price)
{
strcpy(Name,name);
Amount = amount;
Price = price;
}
void CountTotal(void)
{
Total_value = Price * Amount;
}
void GetName(char name[])
{
strcpy(name,Name);
}
int GetMount(void)
{
return Amount;
}
float GetPrice(void)
{
return Price;
}
float GetTotal(void)
{
return Total_value;
}
};
int main() {
CGoods cg1;
cg1.RegisterGoods("c++", 23, 32);
cout<<cg1.GetPrice()<<endl;
cout<<cg1.GetMount();
return 0;
}
char name[] as a function parameter is equivalent to char *name while your string literal has a type const char [4] which can only be (safely) converted to const char *, so you have to change your parameter like this:
void RegisterGoods(const char *name, int amount, float price)
and here:
// Renamed to SetName given that it's what this function actually does
void SetName(const char *name)
In general though you shouldn't use plain char arrays to store strings in C++, you should instead prefer using std::string:
std::string Name;
...
void SetName(std::string name)
{
// take advantage of move semantics to avoid redundant copying
// if you are using C++11 and beyond
Name = std::move(name);
}
Don't use c-constructs for things, c++ has better answers. char-pointers can lead to unwanted behaviors and nasty buffer overflow exploits and so on. It is far better to use a std::string.
Change your member-function RegisterGoods to:
void RegisterGoods(std::string const & name, int const amount, float const price)
{
Name = name;
Amount = amount;
Price = price;
}
and your declaration of Nameto:
private:
std::string Name;
your return function GetName to:
std::string GetName() const
{
return Name;
}
OR
void GetName(std::string & name) const
{
name = Name;
}
also add the include for std::string:
#include <string>
Tip for a better code... don't use using namespace std. std is a enormously huge namespace. Unintentionally you may override a function out of std and you end up with a nearly undebuggable error.
Also define your parameters in setter functions as const, so you can't change the value of it unintentionally.
Is that means that we don't need strcpy and char in c++ anymore? Because i replaced all the 'char' with string and its funktion also. like this:
private:
std::string Name;
public:
void RegisterGoods(const string name, int amount, float price)
{
Name=name;
Amount = amount;
Price = price;
}
const std::string GetName()
{
return Name;
}
Related
This class takes in a name, job title, which are both stored in a char array, and age. An “Invalid conversion from ‘char *’ to ‘char’ occurs when I run the program. I believe I am using the char arrays incorrectly, but am unsure what the issue is. The program works perfectly when using strings. Can you explain what I am doing wrong and how to fix my code? Please also explain how the errors show me what is wrong.
Thank you in adavance.
Header file (emplyee.h)
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
/*No need for passing arguments into the functions since they can
* call the variables declared in the private access specifier. */
class Employee
{
private:
char Name[20], Jobtitle[30]; //Why not working ?
int Age;
public:
Employee(char, int, char);
char getname(); /*Could having the name of the function the same as the variables cause a problem ? Yes it will*/
int getage();
char getjobtitle();
};
#endif // EMPLOYEE_H
Source File (employee.cpp)
#include "employee.h"
Employee::Employee( char n[20], int a, char j[30] )
{
Name = n; Age = a; Jobtitle = j;
}
char Employee::getname()
{
return(Name);
}
int Employee::getage()
{
return(Age);
}
char Employee::getjobtitle()
{
return(Jobtitle);
}
Error messages print screen
Avoid char arrays (in most situations i.e. -03 is not good enough for what you want)
Use std::string. This is how it would look like.
Employee.h:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
#include <string>
class Employee{
private:
std::string Name, JobTitle;
int Age;
public:
Employee(std::string Name, int age, std::string JobTitle);
std::string getName();
int getAge();
std::string getJobTitle();
};
#endif
Employee.cpp
#include "employee.h"
#include <string>
Employee::Employee(std::string n, int a, std::string j){
Name = n;
Age = a;
JobTitle = j;
}
std::string Employee::getName(){
return Name;
}
int Employee::getAge(){
return Age;
}
std::string Employee::getJobTitle(){
return JobTitle;
}
main.cpp:
#include "employee.h"
#include <iostream>
int main(){
Employee e("Hemil", 16, "NA");
std::cout << e.getName() << "\n"
<< e.getAge() << "\n"
<< e.getJobTitle() << "\n";
}
Note: This will not work in Turbo C++
char getname();
means you are gonna return one char which is not correct because
char Name[20]
is a char array so you may want return the pointer to that array (which is of type char*) so your prototype should be
char* getname();
same goes for title
enter code here
Name and Jobtitle are arrays of char's you should use
strcpy(Name, n); and
strcpy(Jobtitle, j);.
Your getname and gettitle functions should be written as:
char *Employee::getname()
char *Employee::getjobtitle().
OK here is my code. I have struct named employee and it has a member char* name. How do I change the value of name?
struct employee {
char* name;
int age;
};
int main()
{
struct employee james;
james.age=12; // this line is fine
james.name = "james"; // this line is not working
cout << james.name;
return 0;
}
Use std::string instead of char* pointer, it will work fine
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Or
If you want to use char* pointer then use const char* name it will work.
#include <iostream>
struct employee {
const char* name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Any literal string value you enter into your source code (such as "james") is by definition a const char* value, the const meaning it may not be altered at program runtime. In your class the name member is declared to be of type char* which is not const and so may be altered at runtime. Your compiler does not allow you to assign a const char* value to a variable of type char* to maintain the invariant that a value of type const char* may not be modified. (The other way around is fine of course; you may assign a char* value to a variable of type const char*.
To fix this with the fewest characters, you must change char* name to const char* name in your employee struct definition. However, I agree that the best thing to do is change it to a std::string member as #Hamza.S laid out in their answer. The std::string class has an assignment operator that builds it out of a const char* value, so the line james.name = "james" in their answer essentially sets the std::string equal to the const char* value "james".
If you are keen on using char*, you could do something like this :
#include <iostream>
#include <string.h>
#include <stdlib.h>
struct employee {
char *name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = (char *)malloc(sizeof(char) * 10);
strcpy(james.name, "James");
std::cout << james.name << std::endl;
return 0;
}
Or else you could use std::string in your struct like this :
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
You can try using strcpy
strcpy(james.name, "james");
I have a class BankAccount with two string members - name and num. What I want is to assign values to these objects when I create them (when the constructor is called). However the compiler says No instance of constructor matches the argument list when I try to create an object.
I would like to ask why is that?
// hwk-2.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class BankAccout {
char name[23];
char num[15];
double sum;
public:
BankAccout(char *nm, char *nr, double s) {
strcpy(name,nm);
strcpy(num, nr);
sum = s;
}
};
int main()
{
BankAccout k("Peter", "0403940940", 34.21);
}
as a coffee break exercise here is more idiomatic version
#include "pch.h"
#include <iostream>
#include <string>
class BankAccount {
std::string name_;
std::string num_;
double sum_;
public:
BankAccount(std::string name, std::string num, double sum) {
name_ = name;
num_ = num;
sum_ = sum;
}
};
int main()
{
BankAccount k("Peter", "0403940940", 34.21);
}
The signature of the constructor does not match.
This one will match:
BankAccount(const char *nm, const char *nr, double s);
EDIT:
The reason is the way you are calling the constructor in the main function. You are giving literal strings as parameters. These literals are const, you cannot change them at runtime. Thus you will pass pointers to const char*.
This is very obvious if you look at this opposing example. This is a way that would be compatible with the old signature BankAccout(char *nm, char *nr, double s);.
int main(int argc, char* argv[])
{
char name[] = "hello";
char number[] = "1234";
std::cout << "name before: " << name << std::endl;
BankAccount k(name, number, 8.5);
// name and number are not const,
// you can change them :
name[2] = 'x';
name[3] = 'x';
std::cout << "name after: " << name << std::endl;
return 0;
}
An even simpler version, if you don’t need to have additional functionality in the class: just use a struct.
#include <string>
struct BankAccount {
std::string name;
std::string number;
double balance;
};
int main() {
BankAccount account{"Joy", "44", 43.};
}
So I am trying to read in a file using private class variables. I am unsure how to display the file. There might be another way to do this, but this is what I could think of. Note, its my first project using classes and private and public/private members. Was I on the right path atleast? I keep getting an error for the int main function. How can I fix it?
This is my main:
#include "Record.h"
#include <sstream>
int main ()
{
Record employee;
ifstream myFile;
myFile.open("Project 3.dat");
string str;
int i=0;
if (myFile.is_open())
{
while (getline(myFile, str))
{
istringstream ss(str);
ss >> employee.get_name(str) >> employee.get_id(stoi(str)) >>
employee.get_rate(stoi(str)) >> employee.get_hoursWorked(stoi(str));
}
}
return 0;
}
This is my header:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Record
{
private:
string name;
int id;
double rate;
double hours;
public:
Record();
Record (string n, int empid, double hourlyRate, double hoursWorked);
// constructor
void read_data_from_file();
double calculate_wage();
void print_data();
/* ASETTERS AND GETTERS */
void set_name (string n);
string get_name();
void set_id (int empid);
int get_id();
void set_rate (double hourlyRate);
double get_rate();
void set_hoursWorked(double hoursWorked);
double get_hoursWorked();
/* END OF SETTERS AND GETTERS */
};
This is my cpp
#include "Record.h"
Record::Record():name(), id(0), rate(0), hours(0) {} //default constructor
must be implemented first
Record::Record(string n, int empid, double hourlyRate, double hoursWorked)
{
name = n;
empid = id;
hourlyRate = rate;
hoursWorked = hours;
}
//
void Record::set_name(string n)
{
name = n;
}
string Record::get_name()
{
return name;
}
//
void Record::set_id(int empid)
{
id = empid;
}
int Record::get_id()
{
return id;
}
//
void Record::set_rate(double hourlyRate)
{
rate = hourlyRate;
}
double Record::get_rate()
{
return rate;
}
//
void Record::set_hoursWorked(double hoursWorked)
{
hours = hoursWorked;
}
double Record::get_hoursWorked()
{
return hours;
}
//
double Record::calculate_wage()
{
return (rate * hours);
}
There are some issues with your code that I can see. most of your problems aren't related to your question (I mean using a class or private/public members). you have more basic misunderstandings. So here's some explanation that might help you:
1- Using functions : You have some troubles using your defined functions, A function can have multiple input parameters and one return value. basically it's like this return_type function_name(parameter_type param1, ...). it means that if you call this function you need to pass param1,... and expect your function operation and then have a return value of return_type. You defined some set and get functions. if you want to set something you should call set function and pass your desired value to it and it will copy your value to your defined member data, after that you can call get function to retrieve that value. So when you call get function with parameter it will raise error. Here you want to call set function.
2- Using stoi : As you can see you are getting error on using stoi function too, this is a function for converting string to integer, The thing that you missed here is that this function declared in std namespace. If you want to use it you need to use it like this std::stoi(str). one other thing, using namespace std is a bad practice.
3- Design matters : In OOP design, a class must have a purpose and an actual job to do. It might be an interface to abstract class but a bunch of set and get functions will not fulfill the need to create a class. Here if your class is going to do file operations, it's OK, but as far as you shared your code it's just some set and get functions.
I am new to this. Basically I just learnt how to use class in C++. When I try to print out, the values just seem to be 0. Can anyone help me out? Its supposed to print out:
Susan Myers 47899 Accounting Vice President
Mark Jones 39119 IT Position
Joy Rogers 81774 Manufacturing Engineer
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
private:
string name;
int idNumber;
string department;
string position;
public:
Employee()
{
name=" ";
idNumber=0;
department=" ";
position=" ";
}
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
Employee(string, int)
{
string n;
int id;
name=n;
idNumber=id;
}
void setName(string)
{
string n;
name=n;
}
void setId(int)
{
int id;
idNumber=id;
}
void setDepartment(string)
{
string d;
department=d;
}
void setPosition(string)
{
string p;
position=p;
}
string getName() const
{
return name;
}
int getId() const
{
return idNumber;
}
string getDepartment() const
{
return department;
}
string getPosition() const
{
return position;
}
};
int main()
{
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<setw(6)<<"ID Number"<<setw(10)<<"Department"<<setw(12)<<"Position"<<endl;
cout<<e1.getName()<<setw(6)<<e1.getId()<<setw(10)<<e1.getDepartment()<<setw(12)<<e1.getDepartment()<<endl;
cout<<e2.getName()<<setw(6)<<e2.getId()<<setw(10)<<e2.getDepartment()<<setw(12)<<e2.getDepartment()<<endl;
cout<<e3.getName()<<setw(6)<<e3.getId()<<setw(10)<<e3.getDepartment()<<setw(12)<<e3.getDepartment()<<endl;
return 0;
}
This is what you get when you rely on guesswork rather than properly reading an introductory textbook on C++
A constructor of the Employee class which (apart from a blank line that I've removed) you define as
Employee(string, int, string, string)
{
int id;
string n,d,p;
name=n;
idNumber=id;
department=d;
position=p;
}
has the following effects.
The four arguments passed by the caller are ignored, since they are not named.
Four default-initialised variables (id, n, d, and p) are defined local to the constructor body. id will be uninitialised. The others, since they are std::string, are default-initialised (to an empty string)
The next four statements copy those variables into class members. The result is that initialising idNumber has undefined behaviour (since id is uninitialised) and the three strings are initialised to empty strings.
To get the effect that (I assume) you intend, change this to;
Employee(std::string n, int id, std::string d, std::string p)
{
name=n;
idNumber=id;
department=d;
position=p;
}
Note that I'm calling string by its full name std::string. That allows removing the using namespace std which (among other things) is BAD practice in header files.
Even better, change this to
Employee(const std::string &n, int id, const std::string &d, const std::string &p) :
name(n), idNumber(id), department(d), position(p)
{
}
which passes the strings by const reference (avoids additional copies of std::strings) and uses an initialiser list instead of assigning to members in the constructor.
Similar comments apply to ALL of the member functions of Employee, except that only constructors can have initialiser lists.
Errors made
Presentation
Your code is extremely cluttered, and has much irrelevant stuff.
Syntax
void setPosition(string){
Here your function has no argument! What is string?
Code
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee{
public:
string name;
int idNumber;
string department;
string position;
void setName(string n){
name=n;
}
void setId(int k){
int id;
idNumber=id;
}
void setDepartment(string d){
department=d;
}
void setPosition(string p){
position=p;
}
string getName(){
return name;
}
int getId(){
return idNumber;
}
string getDepartment(){
return department;
}
string getPosition(){
return position;
}
};
int main(){
Employee e1;
Employee e2;
Employee e3;
e1.setName("Susan Meyers");
e2.setName("Mark Jones");
e3.setName("Joy Rogers");
e1.setId(47899);
e2.setId(39119);
e3.setId(81744);
e1.setDepartment("Accounting");
e2.setDepartment("IT");
e3.setDepartment("Manufacturing");
e1.setPosition("Vice President");
e2.setPosition("Programmer");
e3.setPosition("Engineer");
cout<<"---------------------------------------"<<endl;
cout<<"Name"<<" "<<"ID Number"<<" "<<"Department"<<" "<<"Position"<<endl;
cout<<e1.getName()<<" "<<e1.getId()<<" "<<e1.getDepartment()<<" "<<e1.getPosition()<<endl;
cout<<e2.getName()<<" "<<e2.getId()<<" "<<e2.getDepartment()<<" "<<e2.getPosition()<<endl;
cout<<e3.getName()<<" "<<e3.getId()<<" "<<e3.getDepartment()<<" "<<e3.getPosition()<<endl;
}
Output
---------------------------------------
Name ID Number Department Position
Susan Meyers 32767 Accounting Vice President
Mark Jones 32767 IT Programmer
Joy Rogers 32767 Manufacturing Engineer
Explanation
I have shortened your code by 50%(shows how much redundant stuff you had), and here is a working code.
void setDepartment(string d){
department=d;
}
Here, string d is defined IN the function as an argument. Note that your code also cout<< department twice, and I have corrected that for you in my above code.
Hope this helps.