How can I concatenate the data section (private: char crctr;) of a class called
ID: 3848086 • Letter: H
Question
How can I concatenate the data section (private: char crctr;) of a class called Char with the parameter (char c) and return the two characters as a string? I strictly must use string operator+ (char c) format, which is to be an accessor function. So far with my code, I am getting a character plus a somehow converted int form of char c...
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class Char
{
private:
char crctr; //data member
public:
Char(char ch)//constructor with parameter
{
crctr=ch;
}
//accessor
char toChar()
{
return crctr;
}
string operator+(char c) {return crctr + to_string(c);}
};
int main()
{
Char cha('A');
cout << cha.operator+('B') << endl; //result is A66 ??????????????????
return 0;
}
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class Char
{
private:
char crctr; //data member
public:
Char(char ch)//constructor with parameter
{
crctr=ch;
}
//accessor
char toChar()
{
return crctr;
}
string operator+(char c) {return crctr + to_string(c);}
};
int main()
{
Char cha('A');
cout << cha.operator+('B') << endl; //result is A66 ??????????????????
return 0;
}
Explanation / Answer
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class Char
{
private:
char crctr; //data member
public:
Char(char ch)//constructor with parameter
{
crctr=ch;
}
//accessor
char toChar()
{
return crctr;
}
string operator+(char c) {return crctr + to_string(c);}
};
int main()
{
Char cha('A');
cout << cha.operator+('B') << endl; //result is A66 ??????????????????
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.