Is it possible to use a string with classes? Even if you are using a class specification file and implementation file? I need to have 3 member variables that need to store a string. Or is an array of characters a better fit when it comes to classes?

Recommended Answers

All 4 Replies

Not only is it possible, it's recommended that you use the std::string class instead of C-style strings. I imagine you've tried this already and gotten an error, which prompted you to ask an overly generic question when posting your code and asking a specific question will get your problem solved faster.

Thanks a lot. Now I'm having problems with my constructor and its arguments that contain strings. I have three constructors, one being a default constructor(this one turns all the member variables to null. Another one accepts 4 arguments (three strings and one int). The last one accepts 2 arguments.

What I'm I doing wrong?

THIS IS THE .h FILE

#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include <string>
const int SIZE = 51;
class Employee {
	private:
		string name;
		int idNumber;
		string department;
		string position;
	public:
		Employee(string, int, string, string);  //Constructor #1
		Employee(string, int);  //Constructor #2
		Employee();   //Constructor #3

		//mutator member functions
		void setName(string);
		void setId(int);
		void setDep(string);
		void setPos(string);

		//accessor member functions
		string getName() const
			{return name;}
		int getId() const
			{return idNumber;}
		string getDep() const
			{return department;}
		string getPos() const
			{return position;}
};



#endif

My errors include this no instance of overloaded function "Employee::Employee" matches the specified type which occurs in the constructors that contain strings.
Another error occurs at the set functions that contain strings as well. member "Employee::string" is not a type name

#include "Employee.h"


using namespace std;

Employee::Employee(string n, int num, string dep, string pos){
	name = n;
	idNumber = num;
	department = dep;
	position = pos;
}

Employee::Employee(string n, int num){
	name = n;
	idNumber = num;
	department = " ";
	position = " ";
}

Employee::Employee(){
	name = " ";
	idNumber = 0;
	department = " ";
	position = " ";
}

void Employee::setName(string n){
	name = n;
}

void Employee::setId(int num){
	idNumber = num;
}

void Employee::setDep(string dep){
	department = dep;
}

void Employee::setPos(string pos){
	position = pos;
}

Your header file needs to be using namespace std as well, or declare all of your string variables like std::string myVariable

At work right now, so I don't have access to my compiler. I will mess with it when I get home. Thanks a lot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.