I have a Client class, which receives an std::string variable called emailAdress. This is what the code looks like now, and it works:
private:
const std::string email;
Client::Client(std::string emailAddress) : email{emailAddress}
{
}
Now, I want to check if the email contains characters like an # or a valid name with no strange characters. I want to do this with regex.
Now, my question is, how do I initialize the const std::string email variable after changing the parameter variable? It says it doesn't want to because it is a const variable, that is why it is in the initialization list of the constructor right now.
You can pass the parameter to a function, and let the function return the modified string.
class Client {
private:
const std::string email;
static std::string validateEmail(std::string email) {
// ...
return modifiedEmail;
}
public:
Client::Client(std::string emailAddress) : email{validateEmail(std::move(emailAddress))}
{
}
};
Related
So basically at first I wanted to change the value of CSubject "AE" with the use of a get method but, after seeing some documentation about it, doing this will cause errors like "expression must be a modifiable lvalue". So it's not possible to do such thing .
For something similar we can use a set method in this case, so that's what I did.
However, after compiling I keep geeting an error saying:
Undefined reference to CSubject::CSubject`
Why is that?
class CSubject
{
public:
CSubject() = default;
CSubject(std::string m_Name,unsigned m_SubjNr);
void setName(std::string m_Name){ Name= m_Name;}
std::string getName(){return Name;}
private:
unsigned SubjNr;
std::string Name;
};
int main()
{
CSubject a("test",3);
a.setName("Testing");
cout << a.getName();
return 0;
}
You have declared a CSubject constructor taking a std::string and an unsigned argument but have never provided an actual definition for it! Thus, the linker fails when that (used) constructor is not present in the compiled code.
To fix this, either add an 'inline' definition of that constructor, as shown here (using an initializer list for brevity):
class CSubject {
public:
CSubject() = default;
CSubject(std::string m_Name, unsigned m_SubjNr) : SubjNr{ m_SubjNr }, Name{ m_Name } {}
void setName(std::string m_Name) { Name = m_Name; }
std::string getName() { return Name; }
private:
unsigned SubjNr;
std::string Name;
};
Or, keeping your class declaration as it is, you can provide an 'out-of-body' definition of the constructor, elsewhere in the code, like this (here using 'old-style' long-hand member initialization):
CSubject::CSubject(std::string m_Name, unsigned m_SubjNr)
{
Name = m_Name;
SubjNr = m_SubjNr;
}
Use one or the other, but not both!
I'm a newbie in developing with C++.
I get an error in "this->Buchtitel = buchtitel;" and can't understand why. I have to use const when initializing the variables in Book.h. The Error-Code is: E0349
Book.h
std::string const Buchtitel;
std::string const Autor;
std::string const Anschaffungsdatum;
bool const Status;
Book.cpp
void Book::setBuchtitel(std::string buchtitel) {
this->Buchtitel = buchtitel;
}
void Book::setAutor(std::string autor) {
this->Autor = autor;
}
void Book::setAnschaffungsdatum(std::string anschaffungsdatum) {
this->Anschaffungsdatum = anschaffungsdatum;
}
void Book::setStatus(bool status) {
this->Status = status;
}
How should "setBuchtitel" be written so it doesn't throw an error?
The value of a const variable can only be set during initialization of the variable. For a member variable that's as a default member initializer
std::string const Buchtitel = "Das Boot";
or in the constructor's member initializer list
book(string titel): Buchtitel{titel}
{
}
The value cannot be set anywhere else. In this case the default member initializer is next to useless to you because if it is used exclusively, all books will have the same title.
This makes writing a setter for a const member variable impossible.
How can we use const std::string variable defined in one function to be used in another function of the same program.
int sample::convert()
{
fun()
{
//returns string;
}
const std::string sender = fun()
}
void sample::write()
{
//I want to use sender variable here like below
std::string var;
var = sender;
}
No that's not possible.
Why don't you have sender as a member variable and make sample a class if it is currently a namespace?
If the actual problem is that you don't know how to define constant member variables, it's just like you define it in the function itself:
class sample
{
const std::string sender = "sample";
// Other members...
};
There are two known methods.
First, return the string to use it somewhere (it's probably not what you wanted, but it'll work).
std::string sample::convert()
{
const std::string sender = "sample"
return sender;
}
void sample::write()
{
//I want to use sender variable here like below
std::string var;
var = sender();
}
Or, better declare this variable as a class member variable:
class sample {
std::string sender = "sample"; // if not it's going to be modified, then use 'const'
public:
...
}
I got the answer finally.
We need to declare a char * globally. Then using const_cast <char *> we can convert the constant string to char and assign it.
Example:
in .h file:
char * abc;
in .cc file:
func()
{
const std::string cde = "Hello";
//now to use this constant string in another function,we use const cast and
//assign it to abc like below
abc = const_cast <char *>(cde.c_str());
}
I created a singleton class
class AreaDataRepository {
private:
AreaDataRepository();
AreaDataRepository(const AreaDataRepository& orig);
virtual ~AreaDataRepository();
Way onGoingWay;
public:
static AreaDataRepository& Instance()
{
static AreaDataRepository singleton;
return singleton;
}
void SetOnGoingWay(Way onGoingWay);
Way const & GetOnGoingWay() const;
};
void AreaDataRepository::SetOnGoingWay(Way onGoingWay) {
this->onGoingWay = onGoingWay;
}
Way const & AreaDataRepository::GetOnGoingWay() const {
return onGoingWay;
}
header file of Way
class Way {
private:
std::string id;
std::string name;
public:
Way();
Way(const Way& orig);
virtual ~Way();
void SetName(std::string name);
std::string const & GetName() const;
void SetId(std::string id);
std::string const & GetId() const;
};
Then i'm created a Way object and set vales of id and name.
Way wayNode;
wayNode.SetId("123");
wayNode.SetName("jan")
AreaDataRepository::Instance().SetOnGoingWay(wayNode);
After assign OngoingWay accessing it from another class.
std::cout << AreaDataRepository::Instance().GetOnGoingWay().GetId();
the vale is not printing.
I'm going psychic here.... and I divine that your implementation of SetId is like this:
void SetId(std::string id) { id = id; }
that does not set the member variable, that sets the parameter to itself. And since your constructor most likely set the member variable id to "" you're printing empty strings. Either change the name of the parameter (to newId for example) to avoid the conflict or change the implementation to:
void SetId(std::string id) { this->id = id; }
As proof of this claim here's the result for the first version, as you see it prints nothing. And here is the result for the second, as you can see it prints the number.
The problem boils down to this: you have function parameter names that are the same as the name of your member variables and the function parameters are shadowing/hiding the member variables.
The only place this cannot happen is in a constructor's initialization list:
class Foo {
int x;
public:
Foo(int x): x(x) {} // <-- this works
void SetX(int x) { x = x; } // <-- this won't the parameter is hiding the member variable
};
Demo for the above snippet
std::cout is buffered in most implementations, if not in all. That means, the stream will wait for you to end a line before writing out any data. So, you can easily fix this by changing your output statement to
std::cout << AreaDataRepository::Instance().GetOnGoingWay().GetId() << std::endl;
Let's say I have the following:
char cipan[9];
then what should I pass to the function? how about the get and set method??
I'm currently doing like this
set method
void setCipan(char cipan[]){
this->cipan = cipan;
}
and the get method
char getCipan(){
return cipan;
}
and I get an error when compiling??
Im totally blur.. can someone explain what should i pass to the function??
class userData{
private:
string name;
char dateCreate[9];
void userDataInput(string name,char dateCreate[]){
this->name = name;
this->dateCreate = dateCreate;
}
public:
//constructor
userData(string name){
userDataInput(name,dateCreate);
}
userData(string name,char dateCreate[]){
userDataInput(name,dateCreate);
}
//mutator methods
void changeName(string name){this->name = name;}
void changeDateCreate(char *dateCreate){this->dateCreate = dateCreate;}
//accesor methods
string getName(){return name;}
char *getDateCreate(){return dateCreate;}
};
I'd do the following:
void setCipan(const char* new_cipan)
{
strcpy(cipan, new_cipan);
}
const char* getCipan() const
{
return cipan;
}
Of course, the better approach is to use std::string:
void setCipan(const string& new_cipan)
{
cipan = new_cipan;
}
string getCipan() const
{
return cipan;
}
Constructor's purpose is to initialize class variables. I think it's unnecessary to call another method in the constructor to do initialization.
void userDataInput(string name,char dateCreate[]){
this->name = name;
this->dateCreate = dateCreate; // Both the dateCreate are class variables.
}
userData(string name){
userDataInput(name,dateCreate); // dateCreate is already a class variable.
}
dateCreate is the class scope variable. You are just passing it to a method, and re-assigning the same to dateCreate. Assignment operation doesn't copy elements of one array to another and are invalid operations.
To copy array elements, use std::copy instead.