I am learning about structures now and I am trying to create default values for each variable of that structure type. My testing code is as follows:
#include<iostream>
using namespace std;
int main (void){
// DECLARING THE STRUCTURE
struct str_client{
char name[20] = "\0";
int age = 0;
double money = 0.00;
};
// DECLARING A VARIABLE OF THAT STRUCTURE TYPE (IN THIS CASE, AN ARRAY).
str_client client[3];
return (0);}
Is this initialization the correct way to do it?
Use constructor.
Since class and struct are similar.
struct str_client{
string name;
int age;
double money;
str_client()
{
name = "";
age = 0;
money = 0.0;
}
};
Edit
Using Member Initializer list will improve performance
struct str_client{
string name;
int age;
double money;
str_client()
: name(""), age(0), money(0.0)
{
}
};
Related
I have created an array dynamically of structures and now i am willing to pass it to function.What is the correct method of doing it?What should i put in parameter of function in MAIN for doing it?
void function(Data *family)
{
//code
}
int main()
{
struct Data{
string name;
int age;
string dob;
};
Data *family = new Data[3];
function(Data); //ERROR in parameter i guess!
}
It is better to use more safe ways using std::vector or std::shared_ptr. Because it is easy to make a mistake when you use raw pointers.
If you really need to use raw pointer than you need fix your code:
#include <string>
#include <iostream>
// "Data" should be declared before declaration of "function" where "Data" is used as parameter
struct Data {
std::string name;
int age;
std::string dob;
};
void function(Data *family)
{
std::cout << "function called\n";
}
int main()
{
Data *family = new Data[3];
// fill all variables of array by valid data
function(family); // Pass variable "family" but not a type "Data"
delete[] family; // DON'T FORGET TO FREE RESOURCES
return 0; // Return a code to operating system according to program state
}
Every c++ programmer needs to learn std::vector, which is a dynamic array:
#include <vector>
struct Data{
string name;
int age;
string dob;
};
void function(const std::vector<Data>& family)
{
//code
}
int main()
{
auto family = std::vector<Data>(3);//family now contains 3 default constructed Data
function(family);
}
Not sure what actually what actually you are looking for, I guess you can try like this:
First define your structure outside from main so it would be accessible as function parameter. Then instead of Data pass object family to the function.
struct Data {
string name;
int age;
string dob;
};
void function(Data *family)
{
//code
}
int main()
{
Data *family = new Data[3];
function(family);
}
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.
How do I initialize the member variables in the following code?
#include <string>
#include <iostream>
using namespace std;
int main()
{
typedef struct Employee{
char firstName[56];
char lastName[56];
};
typedef struct Company {
int id;
char title[256];
char summary[2048];
int numberOfEmployees;
Employee *employees;
};
typedef struct Companies{
Company *arr;
int numberOfCompanies;
};
}
You can add a constructor like this one:
struct Employee{
char firstName[56];
char lastName[56];
Employee() //name the function as the struct name, no return value.
{
firstName[0] = '\0';
lastName[0] = '\0';
}
};
As you are already use std::string as indicated from the #include statement, you should change your classes declarations as follows (and do so outside of main() functions body):
struct Employee {
std::string firstName;
std::string lastName;
};
typedef struct Company {
int id;
std::string title;
std::string summary;
int numberOfEmployees;
Employee *employees;
};
typedef struct Companies{
Company *arr;
int numberOfCompanies;
};
first: u use typedef in a wrong way
typedef struct Employee{
char firstName[56];
char lastName[56];
};
you need the other name for typedef
typedef struct _Employee{
char firstName[56];
char lastName[56];
}Employee;
but since u're using c++ typedef is not needed.
Second: don't declare structs inside the function. Declare them outside of main.
Third: use constructors to initialize members to default value, example:
struct Employee{
Employee()
{
strcpy (firstName, ""); //empty string
strcpy (lastName, "asdasd"); // some value, every object now by default has this value
}
char firstName[56];
char lastName[56];
};
fourth: use std::string class (#include) for easier string handling
fifth: consider to type class instead struct, the only difference between those two, is that class declares the variables as private by default(you can change visibility of variable urself), while struct declares them as public by default.
I am having a error from the compiler telling me that "student" "does not refer to a value" it was to my understanding student.test refers to a value and that value has already be initialized to the variable. I need help
int main() {
ifstream dataIn;
ofstream dataOut;
struct student{
string lastName=" ";
string firstName=" ";
int test1=0;
int test2=0;
int test3=0;
int test4=0;
int test5=0;
};
char grade=' ';
int total=0;
int average =0;
average=averageScore(student.test1, student.test2, student.test3, student.test4,student.test5,student.average, student.total);
The problem is that struct student is a type definition and not a variable declaration.
Therefore, in order to access the fields you should declare a variable of this type, and use the variable and not the class i.e.:
student st;
char grade=' ';
int total=0;
int average =0;
average=averageScore(st.test1, st.test2, st.test3, st.test4,st.test5,st.average, st.total);
(And also, as Mr. Yellow mentioned the average field is not defined for struct student)
I am struggling knowing how to create a class. I want to create a "Player" class and all I want to do is pass in the name while I'll have the other variables start at 0 until they are updated when a game is run (later in the program)
Player::Player(string name_in)
{
name = name_in;
int numOfWins = 0;
int numOfLoses = 0;
int numOfDraws = 0;
int totalMatches = 0;
}
Right now there are lots of errors around numOfWins, numOfLoses, numOfDraws and totalMatches. What can I do to fix this?
Perhaps the error is in your int ... part of assignments, which essentially creates a new local variable in a constructor.
Try this version:
#include <string>
using namespace std;
class Player
{
string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
public:
Player(string name_in)
{
name = name_in;
numOfWins = 0;
numOfLoses = 0;
numOfDraws = 0;
totalMatches = 0;
}
};
You should declare other instance variables in the class declaration, rather than declaring them as locals (which is completely useless).
// This part goes in the header
class Player {
string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
public:
Player(string name_in);
};
Now in the constructor you could use initialization lists:
// This part goes into the CPP file
Player::Player(string name_in)
// Initialization list precedes the body of the constructor
: name(name_in), numOfWins(0), numOfLoses(0), numOfDraws(0), totalMatches(0) {
// In this case, the body of the constructor is empty;
// there are no local variable declarations here.
}
Kinda vague, but I'll take a crack at it. You Probably want:
class Player{
string name;
int numOfWins;
int numOfLosses;
int numOfDraws;
int totalMatches;
Player(string name_in)
};
Player::Player(string name_in){
name = name_in;
numOfWins = 0;
numOfLosses = 0;
numOfDraws = 0;
totalMatches = 0;
}
Haven't used C++ in a while, so this may be faulty.
The errors you get, at least from the snippet you posted are caused for you can't declare variables in constructor - you declare them in class body and initialize in constructor or using another function.
#include <string>
class Player {
public:
Player( std::string const& name_in) : name( name_in),
numOfWins(), numOfLoses(),
numOfDraws(), totalMatches()
{} // constructor
// will initialize variables
// numOfWins() means default
// initialization of an integer
private:
std::string name;
int numOfWins;
int numOfLoses;
int numOfDraws;
int totalMatches;
};
usage:
int main() {
Player( "player_one");
return 0;
}