I'm learning C++, and I'm just messing around with putting classes in separate files for practice. I have a getter function, which returns a string (because the variable is saved as a string). However, from my main() function, I am not sure how to call it. I know the problem is probably that I need to include string somewhere when I call the object, but I have no idea how to format it.
I know this is a pretty newbie questions, but I couldn't find the answer anywhere. Could someone help me out?
(p.s. I'm not trying to get this specific code to work, since it's useless. I'm just trying to learn how to apply it for future reference).
I've tried throwing in string in a couple of places when calling or creating the object, but I always get an error. I know I could get around it by not encapsulating the variable or not having a separate class file, but that's not what I want.
main.cpp
#include <iostream>
#include "usernameclass.h"
#include <string>
using namespace std;
int main()
{
usernameclass usernameobject;
usernameobject.getUsername();
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
usernameclass();
std::string getUsername();
void setUsername(std::string name);
askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include "usernameclass.h"
#include <iostream>
#include "username.h"
#include <string>
using namespace std;
string usernameclass::getUsername(){
return usernameVar;
cout << "test cout" << endl;
}
usernameclass::askUsername(){
string name;
cout << "What is your name?" << endl;
cin >> name;
setUsername(name);
cout << "Ah, so your name is "+usernameVar+", great name I guess!" << endl;
cin.get();
cin.get();
cout << "You're about to do some stuff, so get ready!" << endl;
}
usernameclass::usernameclass(){}
void usernameclass::setUsername(string name){
string* nameptr = &usernameVar;
*nameptr = name;
}
Expected result: runs getUsername() function and returns usernameVar
Actual result: doesn't run the getUsername() function
The current code would not compile, because you have not specified return type of 'askUsername()' routine, which is 'void', I believe.
Other things are good, apart from an output in 'getUsername()', which happens after returning from the function and about which you should have received a warning, I guess.
To the question: you can call that 'get' method in 'main()' as:
cout << usernameobject.getUsername();
Your code should be structured more like this instead:
main.cpp
#include <iostream>
#include "usernameclass.h"
int main()
{
usernameclass usernameobject;
// optional:
// usernameobject.askUsername();
// do something with usernameobject.getUsername() as needed...
return 0;
}
usernameclass.h
#ifndef USERNAMECLASS_H
#define USERNAMECLASS_H
#include <string>
class usernameclass
{
public:
std::string getUsername() const;
void setUsername(std::string name);
void askUsername();
private:
std::string usernameVar = "test";
};
#endif
usernameclass.cpp
#include <iostream>
#include "usernameclass.h"
std::string usernameclass::getUsername() const {
return usernameVar;
}
void usernameclass::setUsername(std::string name) {
usernameVar = name;
}
void usernameclass::askUsername() {
std::string name;
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, std::name);
setUsername(name);
std::cout << "Ah, so your name is " << getUsername() << ", great name I guess!" << std::endl;
std::cout << "You're about to do some stuff, so get ready!" << std::endl;
}
Related
I've got the bare shell of a program with a "BasicObject" class and a randum number generator class implemented. When I run the program, the console closes immediately, and cin functions, system("pause"), etc. have no effect. I suspect a crash, but can't find what the source might be. Any help?
BaseObject.cpp:
#include "BaseObject.h"
#include "RandNumGenerator.h"
#include <iostream>
#include <string>
using namespace std;
BaseObject::BaseObject() {
RandNumGenerator* numGen;
set_id(numGen->generate_randNum_str(5));
delete numGen;
}
BaseObject::~BaseObject() {}
...
//void - sets value of string "id"
void BaseObject::set_id(string newId) {
id = newId;
}
Here's the main function:
#include <iostream>
#include <string>
#include "BaseObject.h"
using namespace std;
int main() {
string userIn = "";
BaseObject* obj;
while (userIn != "q") {
cout << "Id of \"obj\" is " << obj->get_id() << endl;
cout << endl << "Type 'q' to quit." << endl;
cin >> userIn;
}
return 0;
}
Your obj object is not instantiated....
It's crashing, because here
obj->get_id()
obj is not initializated yet. Just a pointer to memory with some random garbage.
You need something like
BaseObject* obj = new BaseObject()
Before you can use obj
im new in the C++ world and coding in general, just started studying getters and setters and made areally simple exercise to practice them, the build seems to have 0 errors and 2 minor warnings, however, when I try to use a function to return a private variable and print it, it simply crashes the program, however, if i use the last function I made "getAccount()" It seems to work just fine.
After some poking, it seems like the problem is with the getter functions, just calling them crashes the program, here's the code:
main.cpp
#include <iostream>
#include "Person.h"
using namespace std;
int main()
{
User user;
user.setUser("someuser");
user.setPassw("somepassword");
cout << user.getPassw() << endl;
cout << user.getUser() << endl;
user.getAccount();
}
Person.h
#define PERSON_H
#include <iostream>
using namespace std;
class User
{
private:
string username;
string password;
public:
string setUser(string usernm);
string setPassw(string pass);
string getUser();
string getPassw();
void getAccount();
};
#endif // PERSON_H
Person.cpp
#include <iostream>
#include "Person.h"
using namespace std;
string User::setUser(string usernm){
usernm = username;
}
string User::setPassw(string pass){
pass = password;
}
string User::getUser(){
return username;
}
string User::getPassw(){
return password;
}
void User::getAccount(){
cout << "Account is:" << endl;
cout << "Username: " + username << endl;
cout << "Password: " + password << endl;
}
Not all functions declared to return values actually return values so you have Undefined Behaviour and anything could happen.
Example:
string User::setUser(string usernm){
usernm = username;
// should return a string here
}
string User::setPassw(string pass){
pass = password;
// should return a string here
}
Apart from that, you assign usernm and pass when you should assign username and password so the set operations does not set the member variables.
just a beginner student learning basic C++. I'm trying to figure out the best way to:
Turn a char array Name of 20 into a string that can be printed.
I found in other Stack Overflow topics to use "str()" such as "str(Name)", but it always comes up 'identifier not found'.
cout << "Name:" << str(Name) << endl;
Set a char array of 20 characters. For some reason, the following gives me errors when declaring. I've tweaked it so many times, but I cannot get why it won't give.
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
Full code I have so far:
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
//Step 1
struct StudentRecord
{
char Name[20];
//Accessor
void printInfo() const;
};
void StudentRecord::printInfo() const
{
cout << "Name:" << str(Name) << endl;
}
int main()
{
//Step 2
StudentRecord TESCStudent;
TESCStudent.Name[20] = {'S','u','p','e','r','P','r','o','g','r','a','m','m','e','r','\0'};
//Step 3
TESCStudent.printInfo();
_getch();
return 0;
}
Given that you are at a very beginner level, just use std::string:
#include <iostream>
#include <conio.h>
#include <string>
struct StudentRecord {
std::string Name;
void printInfo() const {
std::cout << "Name:" << Name << '\n';
}
};
int main() {
StudentRecord TESCStudent;
TESCStudent.Name = "SuperProgrammer";
TESCStudent.printInfo();
_getch();
}
Live demo
The syntax like this:
char Name[20] = {'S','u','p','e','r','\0'};
is used to initialize a variable when you define it. However, in your case,
StudentRecord TESCStudent;
TESCStudent.Name[20] = ...;
You've already defined it on the line before, so you can't "initialize", you have to "assign" it.
This is pretty much why you use std:string instead of char[].
I am trying to call a function inside a class, when I try I get the error "no operator << matches these operands" right before instructor.displayMessage(). Also, am I calling instructor.displayMessage() correctly? I am new to c++
#include <iostream>
#include "GradeBook.h"
using namespace std;
int main()
{
GradeBook gradeBook1("CS101 Introduction to C++ Programming");
GradeBook gradeBook2("CS102 Data Structures in C++");
GradeBook instructor("");
instructor.setInstructorName();
cout << "gradeBook1 created for course: \n" << gradeBook1.getCourseName() << instructor.displayMessage()
<< "\ngradeBook2 created for course: \n" << gradeBook2.getCourseName()
<< endl;
cout << "\nPress any key to exit" << endl;
getchar();
}
Header:
#include <string>
using namespace std;
class GradeBook{
public:
GradeBook(string);
void setCourseName(string);
string getCourseName();
void displayMessage();
void setInstructorName();
string getInstructorName();
private:
string courseName;
string instructorName;
};
I didnt include the functions because I dont think they are part of the problem.
void displayMessage();
This function does not return anything, yet you try to print its return value here:
cout << "gradeBook1 created for course: \n" << gradeBook1.getCourseName() << instructor.displayMessage()
If it actually should return something, then you have to declare it with the correct return type, for example
string displayMessage();
However the name suggests that the function itself prints the output already. So maybe you simply want to call it, like this:
instructor.displayMessage();
in a single line.
If you provide the implementation of displayMessage() I might give a more precise answer.
I am getting a linker error undefined reference to Person::Person when trying to implement my program. The three parts are below. I have been working on fixing it for a few hours now. I know it's probably something simple that I am just not seeing. But I have looked around on the internet and still have not found my answer. So any help would be appreciated.
#ifndef PERSON0_H_
#define PERSON0_H_
#include <string>
class Person // class declaration
{
private:
static const int LIMIT = 25;
std::string lname;
char fname[LIMIT];
public:
Person() {lname = ""; fname[0] = '\0';}
Person(const std::string & ln, const char * fn = "Hay you");
void Show() const;
void FormalShow() const;
};
#endif
#include <iostream>
#include <string>
#include "person0.h"
void Person::Show() const
{
using namespace std;
std::cout << fname << " " << lname << '\n';
}
void Person::FormalShow() const
{
using std::cout;
std::cout << lname << ", " << fname << '\n';
}
#include <iostream>
#include <string>
#include "person0.h"
int main()
{
using namespace std;
Person one;
Person two("Smythecraft");
Person three("Dimwiddy", "Sam");
one.Show();
cout << endl;
one.FormalShow();
cout << endl;
two.Show();
cout << endl;
two.FormalShow();
cout << endl;
three.Show();
cout << endl;
three.FormalShow();
cin.get();
cin.get();
return 0;
}
I am not really a C++ person, so the terminology might be wrong, but I would say that the implementation of the
Person::Person(const std::string & ln, const char * fn)
constructor is missing.