This Is my first post here. I have a question about "using namespace std;". I hope I'm posting this right, but please do tell me If I did something wrong!
**Problem: ** So the problem that occurs Is that when I remove 'using namespace std;' I get an unexpected error which gives me the following error: "identifier 'to_string' is undefined". So my question Is, why Is it that I get this unexpected error. (I have marked below with "<-- this part here") where the error occurs once I remove 'using namespace std;' ". Seems a bit weird to me that I'd have to declare "to_strong" beforehand, but when using namespace std; It somehow declares It for me?
#include <iostream>
#include <string>
using namespace std;
// class name {}
class Person
{
private:
std::string name;
int age;
public:
Person()
{
std::cout << "Constructor called!" << "\n";
// (this) signals we are trying to access the veriables of private
this->name = "N/A";
this->age = 0;
}
~Person() // Destructor is a member function which destructs or deletes an object.
{
std::cout << "Destrouctor called!" << "\n";
}
// Accessors (Getters)
const std::string& getName() const { return this->name; }
const int& getAge() const { return this->age; }
// Modifiers (Setters)
void setName(const std::string name) { this->name = name; }
void setAge(const int age) { this->age = age; }
// Functions
const std::string toString() const
{
return "Name: " + this->name + " Age: " + to_string(this->age); <-- This part here
}
};
you need to use
std::to_string()
std:: means standard namespace
Related
I am trying to compile this C++ code unfortunately, I failed to compile the code below. Can you help me by explaining why I am getting this error ?
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id)
{
strcpy(this->name,name); //string copy
this->id=id;
fee=0;
}
student(char name[10],int id,int fee)
{
student::student(name,id); //calling a constructor of one class
// within a constructor of same class
this->fee=fee;
}
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
Below is the error GCC is complaining about.:
main.cpp|20|error: cannot call constructor 'student::student' directly [-fpermissive]|
As rightly suggested by #sweenish, You must do the constructor delegation in the initialization section. Something like this:
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id)
{
strcpy(this->name,name); //string copy
this->id=id;
fee=0;
}
student(char name[10],int id,int fee): student(name, id) // constructor delegation
{
this->fee=fee;
}
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
Also, an advice for you. You may define the more specialized constructor and delegate the responsibility of less specialized constructors to more specialized ones.
#include <iostream>
#include <cstring>
using namespace std;
class student
{
private:
char name[10];
int id;
int fee;
public:
student(char name[10],int id, int fee): id{id}, fee{fee} // more specialized
{
strcpy(this->name,name); //string copy
}
student(char name[10],int id): student(name, id, 0) { } // less specialized calling the more specialized constructor
void show() //print function
{
cout<<"Name:"<<name<<endl;
cout<<"id:"<<id<<endl;
cout<<"fee:"<<fee<<endl<<endl;
}
};
int main()
{
student s1("DAVID",123);
student s2("WILLIAM",124,5000);
s1.show();
s2.show();
return 0;
}
Here's your code with changes made to get it compiling; I marked the changes with comments.
#include <iostream>
// #include <cstring> // CHANGED: Prefer C++ ways when writing C++
#include <string> // CHANGED: The C++ way
// using namespace std; // CHANGED: Bad practice
class student {
private:
std::string name{}; // CHANGED: Move from C-string to std::string
int id = 0; // CHANGED: Default member initialization
int fee = 0;
public:
// CHANGED: Move from C-string to std::string
student(std::string name, int id)
: name(name),
id(id)
// CHANGED: ^^ Utilize initialization section
{
// CHANGED: Not needed anymore
// strcpy(this->name,name); //string copy
// this->id=id;
// fee=0;
}
student(std::string name, int id, int fee) : student(name, id) {
// CHANGED: Not needed anymore
// student::student(name,id); //calling a constructor of one class
// // within a constructor of same class
// NOTE: Inconsistency with other ctor w.r.t. this->
this->fee = fee;
}
void show() // print function
{
std::cout << "Name:" << name << '\n';
std::cout << "id:" << id << '\n';
std::cout << "fee:" << fee << "\n\n";
}
};
int main() {
student s1("DAVID", 123);
student s2("WILLIAM", 124, 5000);
s1.show();
s2.show();
return 0;
}
Here is the same code, but with the stuff I commented out removed to make it easier to read.
#include <iostream>
#include <string>
class student {
private:
std::string name{};
int id = 0;
int fee = 0;
public:
student(std::string name, int id) : name(name), id(id) {}
student(std::string name, int id, int fee) : student(name, id) {
this->fee = fee;
}
void show()
{
std::cout << "Name:" << name << '\n';
std::cout << "id:" << id << '\n';
std::cout << "fee:" << fee << "\n\n";
}
};
int main() {
student s1("DAVID", 123);
student s2("WILLIAM", 124, 5000);
s1.show();
s2.show();
return 0;
}
The initialization section follows the parameter list and is marked with :. You then initialize each member, in the order they are declared.
In the case of the constructor doing the delegating, you are unable to initialize fee in the initialization section. The error I receive is a delegating constructor cannot have other mem-initializers.
I don't like splitting my initialization like that, and if you insist on delegating constructor calls for this class, implement the most specific constructor and delegate to it with your less specific constructors. I prefer default member initialization as I think it leads to less confusion and written code overall.
The code then compiles and you get the expected output:
Name:DAVID
id:123
fee:0
Name:WILLIAM
id:124
fee:5000
I'm new to the cpp language and I have a problem with my code which I don't know how to solve, I looked here on some other questions people asked about this error, but none of the answers really helped me to solve the problem.
So this is my main function:
#include <iostream>
#include "Person.h"
#include <string>
int main() {
Person p2();
Person p1();
std::cout << p1.toString() << std::endl;
return 0;
}
and here is my Person.h file:
#ifndef PERSON_H_
#define PERSON_H_
#include <string>
class Person {
private:
int age;
std::string name;
int numOfKids;
public:
Person() {
this->age = 0;
this->name = "bob";
this->numOfKids = 5;
}
Person(int agee, std::string namee, int numof);
~Person();
std::string toString();
};
#endif // PERSON_H_
In the main function it marks p1.toString() and says "expression must have class type"
and I don't know what to do, I tried many things and none of them worked.
These kind of statement you write can have ambigous meaning:
Person p2();
(what you want) a variable p2 with type Person and default constructed.
(the compiler thought) a function declaration p2 returning an object of Persion.
Remove the bracket or using the '{}' (c++11) should make things clear:
Person p1{};
Person p2;
Various points to correct:
Person(int agee, std::string namee, int numof);
~Person();
std::string toString();
These three are only declared, not defined. This will result in unresolved external symbol error messages from the compiler.
Correct also the the variable declarations of p1 and p2.
Use this snip as an orientation:
#include <iostream>
class Person
{
private:
int age;
std::string name;
int numOfKids;
public:
Person()
{
this->age = 0;
this->name = "bob";
this->numOfKids = 5;
}
Person(int agee, std::string namee, int numof)
{
// ToDo
}
~Person()
{
// ToDo
}
std::string toString()
{
// ToDo
return "";
}
};
int main()
{
Person p2;
Person p1;
std::cout << p1.toString() << std::endl;
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I want to create a Student object in C++ and it has the properties of name, major, age and id. The object initialization will be done in the main() part and Student object has the get and set methods for all the constructors. I want to print the student objects in the main() part but I get this error:
in C++98 's1' must be initialized by constructor, not by '{...}'
I am using GNU GCC Complier in Codeblocks. I haven't written specifically any code for compiling or debugging.
I tried to initialize the objects by assigning them to this, making them null, giving them zero and random values but they haven't worked.
Student.h file
#ifndef STUDENT_H
#define STUDENT_H
#include <iostream>
#include <string>
using namespace std;
class Student
{
public:
string name, major;
int age, id;
Student(string name, string major, int age, int id);
string getName();
void setName(string name);
string getMajor();
void setMajor(string major);
int getAge();
void setAge(int age);
int getId();
void setId(int id);
};
ostream & operator << (ostream &out, Student &s);
#endif // STUDENT_H
Student.cpp file
#include "Student.h"
#include <iostream>
using namespace std;
Student::Student(string newName, string newMajor, int newAge, int newId)
{
name = newName;
major = newMajor;
age = newAge;
id = newId;
}
string Student::getName(){
return name;
}
void Student::setName(string newName){
name = newName;
}
string Student::getMajor(){
return major;
}
void Student::setMajor(string newMajor){
major = newMajor;
}
int Student::getAge(){
return age;
}
void Student::setAge(int newAge){
age = newAge;
}
int Student::getId(){
return id;
}
void Student::setId(int newId){
id = newId;
}
ostream & operator << (ostream &out, Student &s)
{
out << "Name: " << s.getName() << " Major: " << s.getMajor() << " Age: " << s.getAge() << " Id:" << s.getId() << endl;
return out;
}
Main.cpp file
#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main()
{
Student s1 {"John","MATH",24,123456};
Student s2 {"Steve","ENG",22,654321};
cout << s1 << endl;
cout << s2 << endl;
return 0;
}
I expect to print out the properties of the students as a list but when I run it the program crashes and I get this error:
** in C++98 's1' must be initialized by constructor, not by '{...}' **
I fixed my problem. There were a few problems so here I will explain my solutions in detail.
1-My code is written in C++11 syntax but I was using C++98 syntax so I changed my complier to C++11.
2-My initialization was wrong, I used new variables such as newName, newAge... to change the properties of the Student object.
3-My set methods were wrong so I changed them similar to my initialization.
4-I added an opeator to print out properties more easily.
All the changes are updated for the code in the question
Can anyone tell me why i get the error "name was not declared in the scope when running this?
Thanks.
class lrn11_class{
public:
void setName(string x){
name = x;
}
string getName(){
return name;
}
private:
string lrn11_name;
};
int main()
{
lrn11_class lrn11_nameobject;
lrn11_nameobject.setname("Zee");
cout << lrn11_nameobject.getname() << endl;
return 0;
}
This should work - see comments (BTW use std:: - Why is "using namespace std" considered bad practice?)
#include <iostream>
#include <string>
class lrn11_class{
public:
void setName(const std::string& x){ // Potentially saves copying overhead
name = x;
}
std::string getName() const { // Look up const and its uses
return name;
}
private:
std::string name; // - Used: string lrn11_name; but functions use name!
};
int main()
{
lrn11_class lrn11_nameobject;
lrn11_nameobject.setName("Zee"); // Fixed typo
std::cout << lrn11_nameobject.getName() << std::endl; // Ditto
return 0;
}
You have declare lrn11_name as a member varible for this class. But in set and get functions you are using name.
Other than than you need to call functions as you have defined.
so instead of :-
lrn11_nameobject.setname("Zee");
cout << lrn11_nameobject.getname() << endl;
You have to use following code :-
lrn11_nameobject.setName("Zee");
cout << lrn11_nameobject.getName() << endl;
Make sure that
#include <iostream>
using namespace std;
should be included.
I have just learnt some object oriented programming concepts in Python, but I want to transfer this knowledge to C++, and I have trouble with basic implementation that used to be easy using Python.
#include<iostream>
using namespace std;
class Animal{
char name;
int age;
public:
Animal(char name, int age);
};
Animal::Animal(char name, int age) {
this->name = name;
this->age = age;
}
int main()
{
Animal dog ("Megg", 10);
cout << "Name: " dog.name <<endl;
return 0;
}
When I compile this code, I get a lot of messages, such as:
error: no matching function for call to 'Animal::Animal(const char[5], int)'
note: Animal::Animal(char, int) <near match>
note: candidate expects 1 argument, 2 provided
Thanks!
you don't need to do this->name = name in your constructor definition
"Megg" is a string literal. You can cast "Megg" into const char * but not into a char (this was most likely causing your error).
or better yet. You can use the C++ Standard Library string class std::string
#include <iostream>
#include <string>
class Animal{
std::string name;
int age;
public:
Animal(std::string name, int age);
std::string getName() const;
int getAge() const;
};
Animal::Animal(std::string Name, int Age) {
name = Name;
age = Age;
}
std::string Animal::getName() const {
return name;
}
int Animal::getAge() const {
return age;
}
int main()
{
Animal dog ("Megg", 10);
std::cout << "Name: " << dog.getName() << std::endl; // Error in this line. Missing << between "Name: " and dog.name
return 0;
}
Some additional edits:
You should avoid using using namespace std as it takes everything in the Standard Library (from the files you've included) and puts it in the global namespace. You can instead use the scope resolution operator :: as seen above.
When you start working with multiple libraries you may encounter that both have a class named vector or string, or functions with the same name. The way to avoid this is to specify what namespace you want to use.
or alteratively you can do the following:
using std::cout;
using std::endl;
using std::string;
Additionaly in order for you program to work you need a way to access your object's member variables. You could do this by making the variables public or the better practice is to add accessor functions.