I'm building custom operators and im having problems when passing parameters to them.
For example
class test{
public:
test operator[](vector <string> s){
test a;
return a;
}
};
Now if I wanted in my main program to do something like this
int main(){
test d;
vector<string> s;
s.push_back("bla");
d[s];
}
I get a bunch of errors. Is it because I need to have const somewhere or I don't know.
Also I have built in a custom operator for printing out the class test ( << operator ). Now I don't get compile error when calling d[s] in main program but I get compile error when calling cout<< d[s] in main program. The operator << is working because I tested it with simple cout<< d
return test;
test is a type. You can't return a type. Perhaps you meant:
return a;
But then you have another problem because you're returning a reference to a local variable. The object a will be destroyed when the function returns (because that is its scope) and so the reference will be left dangling.
Code working fine using gcc compiler.
#include <string>
#include <vector>
using namespace std;
class test{
public:
test operator[](vector <string> s){
test a;
return a;
}
};
int main(){
test d;
vector<string> s;
s.push_back("bla");
d[s];
}
Notwithstanding the errors that other folk have already pointed out (dangling reference, returning a type rather than the value), note that if you intend to override [], you should also consider overriding the pointer deference operator (unary *) too as many folk use them interchangeably.
Related
int main() {
// Complete the program
string a,b;
getline(cin,a);
getline(cin,b);
cout<<a.size()<<" ";
cout<<b.size();
string c=a+b;
cout<<endl<<c;
swap(a[0],b[0]);
cout<<endl<<a<<" "<<b;
return 0;
}
void swap(string s1,string s2){
string temp=s1;
s1=s2;
s2=temp;
}
Well the target is to swap the first element of both strings, but I created a general function for that and even got it right. But, unexpectedly, I didn't use pass by reference or pointer! Even then, the changes are permanent when I try to output a and b in the end!
Logically it shouldn't work but it is working. Is it something to do with the strings?
This is almost certainly due to the fact that, somewhere in code that you have not shown us, you have this line (or something very similar):
using namespace std;
With this line included, then that very namespace std defines a function as follows:
void swap(_Ty& _Left, _Ty& _Right);
Where the _Ty template is replaced with char in your swap(a[0],b[0]); call.
Add a simple cout << "My Swap" << endl; line to your swap function, and you'll see it's not being called.
Highly recommended reading: Why is "using namespace std;" considered bad practice?.
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 6 years ago.
#include <iostream>
#include<string.h>
using namespace std;
char *rt()
{
char a[20];
strcpy(a,"I am a beginner");
cout<<a;
return a;
}
int main()
{
char *a;
a=rt();
cout<<endl;
cout<<a;
return 0;
}
Here I have made a short program for understanding the same....I was expecting the output to be as
I am a beginner
I am a beginner
UPDATE:
But it turned out to be
I am a beginner
ëóG
I have read many articles and post but I am not able to understand their complex language....so I will appreciate a no-nonsense answer ( for a stupid...like me!!)
UPDATE:
Actually, there is one question in my assignment which goes like this
class COMPUTER
{
char chiptype[10];
int speed;
public:
void showdetails()
{
cout<<chiptype;
cout<<"\t"<<speed;
}
void getdetails()
{
cin.getline(chiptype,10);
cin>>speed;
}
};
Here the data has to be read and stored into a binary file....and the records having chiptype as "CD" are to be displayed.
Now my question is that...as the variable chiptype is private so I can't use it for comparison in main()....so I thought of making a function which returned the value stored in chiptype.
And I am not allowed to use std::string as well as node implementation...
char a[20]; is allocated on stack. When the function rt() returns, the stack unwinds and a goes out of scope. Hence you do not get your desired result.
While you are on C++, may I suggest using std::string
Read the comment below:
The other trick is to wrap the array in a struct, and return the
struct. Since a struct is copyable, the array internally becomes
copyable and will not lose scope. See this answer. Then you're not
dealing with pointers at all. See this live example – PaulMcKenzie
Use std::string instead of char[]
#include <iostream>
#include<string>
std::string rt()
{
std::string a("I am a beginner");
std::cout<<a;
return a;
}
int main()
{
std::string a;
a=rt();
std::cout<<std::endl;
std::cout<<a;
return 0;
}
In your original code char a[20] is allocated on the stack and return a; will return a pointer to a stack variable that is no longer valid when you receive it in you main() -- handling strings in c++ should generally be done using std::string as it handles all the nasty memory management that wil kill your program if you aren't careful.
If you have to use pointers and not use std::string, you would need to go the c style way with the risk of having memory leaks if you miss a step or two. The code would look something like this using c style (keeping the cout c++)
#include <iostream>
#include <strings.h>
std::string rt()
{
char *a = malloc(20); // allocate the memory on heap
strcpy(a,"I am a beginner");
std::cout<<a;
return a;
}
int main()
{
char *a;
a=rt();
std::cout<<std::endl;
std::cout<<a;
free(a); // release the memory
return 0;
}
Caution: I don't recommend that you do the above style -- in a real world application you will likely get into trouble by either forgetting to free the memory, or accidentally accessing the memory after it has been free'd
The problem is that the memory of a will be destroyed as soon as program returns from the function. I do not think you should work with dynamic memory at your level of knowledge, so I suggest you define the array outside and just modify it inside the function:
#include <iostream>
#include<string.h>
#define MAX_LENGTH 20
using namespace std;
void rt(char *a)
{
strcpy(a,"I am a beginner");
cout<<a;
}
int main()
{
char a[MAX_LENGTH];
rt(a);
cout<<endl;
cout<<a;
return 0;
}
Furthermore, you should take care that rt is not writing more than MAX_LENGTH characters.
As mentioned by other use std::string instead of char [].
std::string rt()
{
std:: string a = "I am a beginner"; // This statement is equivalent to std::string a("I am a beginner");
std::cout << a "\n";
return a;
}
Main reason of not getting the desired result is " char a[] is allocated on stack, but when function return stack become empty.
P.S : You need to include <string> in your program, to use std::string
I am using C language to upgrade my coding skills.
I designed a simple program because I wanted to easily find the problems what I looked for and arrange the works when I handle many problems as shown in below.
Here is my header file
#pragma once
#ifndef PROBLEM_H
#define PROBLEM_H
namespace PROBLEM_1 { int do_main(); }
typedef int(*MAINFUNC)();
#endif
And below is my source file.
#include "problems.h"
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
typedef int(*MAINFUNC)(void);
map<string, MAINFUNC> func_map;
void initialize_problem_map(void) {
func_map["problem_1"] = PROBLEM_1::do_main;
}
namespace PROBLEM_1 {
int do_main(void) {
cout << "hi" << endl;
return 1;
}
}
int main(void) {
string problem;
initialize_problem_map();
cin >> problem;
if (func_map.find(problem) != func_map.end())
return (*(func_map[problem]))();
return -1;
}
If I input "PROBLEM_1" then, the do_main functions in namespace PROBLEM_1 will be executed. I think that this design helps me organize multiple coding problems.
However, my question is about these two code lines as below.
if (func_map.find(problem) != func_map.end())
return (*(func_map[problem]))();
As you can see, the main fucntion's return type is "int". However, in the if-clause, i think that it return function-pointer. Therefore, I thought that those returning behavior is mismatched with the main function's return type. But, to my surprise, it worked well.
Could u explain this procedures regarding returning types?
func_map[problem], indeed, results in a function pointer. Applying the operator () on it, the function is invoked and the expression results in an int. Dereferencing a function pointer before its invocation is optional. This is symmetric with an optional address taking on a function name for initializing function pointers.
Indeed
func_map[problem]
is a pointer. However, you dereference the pointer with *:
*(func_map[problem])
and call function by adding ():
(*(func_map[problem]))()
which returns "int".
find returns an iterator; if this iterator is end, then the problem does not exist in the map; Because it is not end, it exists, then in the return line the pointer function obtained with [] is used to call it.
So I'm trying to use get/set functions, and I'm having a problem changing the default Astring using the set fuction. Program crashes after when I try to run with this:
#include <iostream>
#include <string>
using namespace std;
class Example{
private:
string m_Astring;
public:
Example()
{
m_Astring="123456789012";
}
string setAstring(string Astring){m_Astring=Astring;}
string getAstring(){return m_Astring;}
};
int main(){
Example test;
test.setAstring("250687354221");
cout<<test.getAstring()<<endl;
return 0;
}
The problem is here:
string setAstring(string Astring){m_Astring=Astring;}
^^^^^^ ^^^^
return a string no return of string
Your program crashes because you never returned anything from this function, and that is undefined.
(I suspect that the crash occurs when destroying the non-existent return value, but I haven't confirmed this.)
// pointer to functions
#include <iostream>
#include <vector>
using namespace std;
struct boo{
string u;
int p;
};
vector <boo> om(boo &bo){
cin >> bo.u;
cout << bo.u;
}
int main(){
string q;
vector <boo> b;
om(b);
}
Ok I need to understand how will I be able to write vector<boo> om(boo &bo) into my main(). I always get some type of error with it and I need help with it. I can't ever call the function into main because I just simply don't know how to call it into main. Well I know how to call om([I just need help with this part]) I have no idea what to fill this in with.
P.S
Sorry this is at the bottom Im a noob with stackoverflow.
Taking a shot in the dark here because this seems to be the most likely intent. If i'm wrong, hopefully it is still instructional.
#include <iostream>
#include <vector>
I removed the using namespace std that was here because it's dangerous. Don't believe me? Do a quick search. StackOverflow is littered with "WTF is going on?" questions that resolve down to "something in the std namespace had the same name as your variable."
struct boo
{
std::string u;
int p;
};
I've left Boo alone to keep it recognizable to the OP. However, descriptive names really help your code explain itself. No one here, excluding the OP, has any clue what a boo represents and how it should be used or what it's members represent and how they should be used. This limits the our ability to assist the OP with debugging support and advice.
On to function om. Again, terrible name. A function name should provide some hints as to what the function does.
Assumptions:
Om is intended to
read in input to get the data required to fill out a boo structure
place that boo structure into main's vector b
With that in mind,
No need to return anything except perhaps an error code if the user fails to enter correct input.
The only thing worth passing in is a reference to the vector. The reference allows the vector supplied by the caller to be modified.
If we knew what a boo was someone might be able to suggest better ways to do this and validate the user input.
void om(std::vector<boo> &bo)
{
boo temp; //start by making a temporary boo
std::cin >> temp.u; // read user input into the temporary boo
// removed the print out here
bo.push_back(temp); // copy the temporary boo into the vector
}
main is altered to remove unused string q and output the contents of vector b
int main()
{
std::vector<boo> b; // usual nagging about non-descriptive name
om(b);
for (boo testboo: b)
{ // print all boos in b
std::cout << testboo.u << std::endl;
}
}
And as one cut-n-paste-able block for trying it out and playing around:
#include <iostream>
#include <vector>
struct boo
{
std::string u;
int p;
};
void om(std::vector<boo> &bo)
{
boo temp; //start by making a temporary boo
std::cin >> temp.u; // read user input into the temporary boo
// removed the print out here
bo.push_back(temp); // copy the temporary boo into the vector
}
int main()
{
std::vector<boo> b; // usual nagging about non-descriptive name
om(b);
for (boo testboo: b)
{ // print all boos in b
std::cout << testboo.u << std::endl;
}
}