can somebody please explain my mistake, I have this class:
class Account
{
private:
string strLastName;
string strFirstName;
int nID;
int nLines;
double lastBill;
public:
Account(string firstName, string lastName, int id);
friend string printAccount(string firstName, string lastName, int id, int lines, double lastBill);
}
but when I call it:
string reportAccounts() const
{
string report(printAccountsHeader());
for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i)
{
report += printAccount(i->strFirstName, i->strLastName, i->nID, i->nLines, i->lastBill);;
}
return report;
}
I receive error within context, can somebody explain why?
I imagine the full error has something to do with "These members are private within context" and some line numbers.
The issue is that i->strFirstName is private from the perspective of the reportAccounts() function. A better solution may be:
class Account{
private:
string strLastName;
string strFirstName;
int nID;
int nLines;
double lastBill;
public:
Account(string firstName, string lastName, int id);
string print() const
{
return printAccount(this->strLastName, this->strFirstName, this->nID,
this->nLines, this->lastBill);
}
};
And then
string reportAccounts() const {
string report(printAccountsHeader());
for(list<Account>::const_iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i){
report += i->print();
}
return report;
}
Another option is to make printAccount take a reference to an Account (friend printAccount(const Account& account)), and it can then access the private variables through the reference.
However, the fact that the function is called print Account suggests that it might be better as a public class function.
You're declaring that function printAccount is friend of class Account. But in the example, you're accessing the members of the class (i->strFirstName ...) in the function reportAccounts. This latter is not declared as friend.
You are missing a semicolon in the class definition.
class Account{
private:
string strLastName;
string strFirstName;
int nID;
int nLines;
double lastBill;
public:
Account(string firstName, string lastName, int id);
friend string printAccount(string firstName, string lastName, int id, int lines, double lastBill);
};
^--- see the semicolon here?
That shouldn't be the whole error.. there should be something more..
by the way your friend syntax seems correct, but in reportAccounts you seem to use all the fields of Account class that are private, like strFirstName and the name of the function is reportAccounts not printAccounts so probably you just made a method friend but you are trying to access private fields with another one.
Related
I was working on homework that my instructor wanted me to write a class named Species with setter and getter functions. I wrote that code but I can't set or get any value when I run it. Can you help me?
class Species
{
private:
string name;
string country;
int population;
int growthrate;
public:
int year;
void setName(string NameS){
NameS=name;
}
void setCountry(string CountryS){
CountryS=country;
}
void setPopulation(int pop){
pop=population;
}
void setGrowthRate(int GrowRth){
GrowRth=growthrate;
}
void setYear(int syear){
syear=year;
}
string getName() {
return name;
}
string getCountry() {
return country;
}
int getPopulation() {
return population;
}
int getGrowthrate() {
return growthrate;
}
double e=2.71828182;
double calculatePopulation() {
int b=growthrate*year;
int a=pow(e,b);
return population*a;
}
};
First of all. Your class has fields like:
string name;
string country;
int population;
int growthrate;
And your methods are like:
void setName(string NameS){
NameS=name;
}
So you want to set NameS value to the name which makes no sense.
You should assign the field like name to be equal to nameS not the opposite.
Generally, a setter should look like this.
void setVariable(const VariableType& var){
this->var=var;
}
What you did was var=this->var.
Btw, you should make your getter-s const
You should use "this" keyword to set the value to object of the class.
this: to refer current class instance variable. The this keyword can be used to refer current class instance variable.
for example:
void setName(string name){
this.name=name;
}
void setGrowthRate(int growthrate){
this.growthrate=growthrate;
"this" is very helpful in please learn more about it.
I'm new in oop and don't know how to specify this problem globally. I have two classes. Client
class Client
{
private:
int code;
string name;
public:
Client(int c, string n);
int getCode();
string getName();
};
Client::Client(int c, string n)
{
this->code = c;
this->name = n;
}
int Client::getCode()
{
return this->code;
}
string Client::getName()
{
return this->name;
}
and Account
class Account
{
private:
int number;
double balance;
double interestRate;
Client* owner;
};
and I have method like this:
Client* Account::getOwner()
{
return this->something;
}
Can you please tell me, how can I get client's code and name from this method?
Can you please tell me, how can I get client's code and name from this method?
The method is called getOwner. A method called getOwner should ... get ... the owner. Nothing else.
If you want to get the owner's name, either write a new method
string getOwnerName() const { return owner->getName(); }
or ...
(better because it reduces coupling between the Account and Client classes, possibly worse because it depends on exposing the owner directly, but then you're already doing that ...)
... just delegate this to the client code:
cout << account->getOwner()->getName();
I have publication and library two classes and in publication class. How to manipulate(as encapsulation) genre, media, and target_age, If I want them to be separate classes. It's not class inside another class.
The genre have more type's as (fiction, non-fiction, self-help, performance) as well as media and age. I have done my research I'm serchin for the proper syntax for it.
class Publication {
private:
string title;
string authore;
string copyright;
Genre genre;
Media media;
Age target_age;
string isbn;
bool checked_out;
string patron_name;
string patron_phone;
public:
void check_out(string patron_name, string patron_phone ){}
void check_in(){}
bool is_checked_out(){}
string to_string(){}
};
The best way to encapsulate is to keep everything private. Create constant getters for stuff that might be read from the outside, and initialize everything in the constructor. After all, things like author/title/etc. should not ever change for an instance of a real book right? Have a look at the following snippet:
class Publication {
private:
string _title;
string _author;
Genre _genre;
public:
void check_out(string patron_name, string patron_phone );
void check_in();
bool is_checked_out() const;
string to_string() const;
string get_title() const { return _title; }
string get_author() const { return _author; }
const Genre& get_genre() const { return _genre; }
Publication(string author, string title, Genre genre) : _author(auth), _title(title), _genre(genre)
{ }
};
First of all, I have only learned a little bit of Java before. It's been only a few days since I started getting friendly with C++ so please don't take this question so basic and please don't degrade my question.
I made a simple source code as follows:
#include <iostream>
using namespace std;
class Car {
public:
void setBrand(string name);
void setPrice(double price);
string getBrand();
double getPrice();
Car();
Car(string name);
Car(string name, double price);
private:
string name;
double price;
};
Car::Car() {
}
Car::Car(string name) {
name = name;
}
Car::Car(string name, double price) {
name = name;
price = price;
}
void Car::setBrand(string name) {
name = name;
}
void Car::setPrice(double price) {
price = price;
}
string Car::getBrand(void) {
return name;
}
double Car::getPrice(void) {
return price;
}
int main() {
Car car;
car.setBrand("Nissan");
car.setPrice(30000);
cout << "Brand: " << car.getBrand() << endl;
cout << "Price: " << car.getPrice() << endl;
return 0;
}
I wanted to make a code that creates an empty instance of a class called Car, set the field values later and print them out on the console.
The code did not make any errors during the compile, but the result I see was totally different from what I expected. It didn't show the brand name and the price was looking even weird, as follows.
Brand:
Price: 6.95322e-310
Somebody help me out! Thank you very much indeed in advance.
The problem you have is that you override the member names with function parameters. You can use this-> to make it explicit or name the member differently.
For example:
void Car::setBrand(string name) {
this->name = name;
}
Or:
void Car::setBrand(string new_name) {
name = new_name;
}
In your constructor and setters, you make no differentiation between the local parameter and the class member.
name = name;
Both the function parameter and the class member are called name. Currently the compiler is assigning the parameter value to itself, and not affecting the class member at all. This is because the function parameter is in a more immediate scope.
Possible solutions:
Specify this when referring to the class member: this->name = name;.
Rename the function parameter: name = _name;.
For the constructor, use initializer lists:
Car::Car(string name, double price)
: name(name)
, price(price)
{ }
There's too much wrong with your code to describe it in prose, so let me present a fixed implementation, and I leave it to you to spot the difference:
#include <string>
class Car
{
private:
static constexpr double kNoPrice = -1.0;
static constexpr const char* kNoName = "[no name]";
public:
// Main constructor: constructs a car with the given name and price.
Car(std::string name, double price)
: name_(std::move(name))
, price_(price)
{}
// Convenience constructors:
Car() : Car(kNoName, kNoPrice) {}
Car(std::string name) : Car(std::move(name), kNoPrice) {}
// Accessors:
const std::string& getBrand() const { return name_; }
void setBrand(std::string name) { name_ = std::move(name); }
double getPrice() const { return price_; }
void setPrice(double price) { price_ = price; }
private:
std::string name;
double price;
};
Some random notes, in no particular order:
Use correct names. It's std::string, not string, mate or buddy. Never ever be abusing namespace std.
Include headers for external names that you need.
Reading uninitialized values is undefined behaviour, so none of your constructors should leave fields uninitialized (like price_).
Give private members consistent names (e.g. foo_ in my example).
Accessors should be const-correct.
Convenience constructors should delegate to one single work-horse constructor.
Pick sensible defaults for initial values of defaulted fields and make them discoverable.
Use move semantics when taking ownership of dynamically managed data (strings, dynamic containers, etc.).
Following is my code where I have to store contacts in a phonebook .
Class contact
{
private:
string name;
double number;
string relation;
int phonebookNum;
public:
Contact()
Contact(Contact& temp) //copy constructor
//set and get functions
};
class phonebook
{
public:
phonebook();
void AddContact(contact temp);
~phonebook();
private:
string name;
vector <contact> vect;
int peopleCount = 0;
};
The problem is that in my .cpp file when I declare my function for Add Contact
void phonebook::AddContact(contact temp)
{
name = temp.getName();
vect.push_back(temp);
peopleCount++;
}
On reading the vect.push_back(temp) part, a separate tab opens up on my CodeBlocks by the name of : vector.tcc and shows an error in that file somewhere
How do I make a vector where I store my contacts and how do I access them ?
Your Contact class has an uppercase C while you pass a lowercase contact to the method phonebook::AddContact.
Declare your method like this
void phonebook::AddContact(Contact temp)
I would also suggest that you choose a way on how you name your classes.
Mixing up lower- and uppercase classes is not a good idea.