Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
im making an operator for comparing objects of my own class 'Paciente', but when calling (const) getters of that class, Im getting errors.
Here I leave the code:
bool operator==(const Paciente& p1, const Paciente& p2){
return (p1.getNombre() == p2.getNombre() && p1.getApellidos() == p2.getApellidos());
}
Here the class Paciente:
class Paciente {
private:
string nombre_;
string apellidos_;
int edad_;
public:
Paciente(const string &nombre="none", const string &apellidos="none", const int &edad=0): nombre_(nombre), apellidos_(apellidos), edad_(edad){};
const string & getNombre(){return nombre_;};
const string & getApellidos(){return apellidos_;};
const int & getEdad() {return edad_;};
string setNombre(const string &nombre){nombre_ = nombre;};
string setApellidos(const string & apellidos){apellidos_ = apellidos;};
int setEdad(const int &edad){edad_ = edad;};
};
Class Paciente is allocated at 'paciente.hpp', and the operator and many more functions at 'functions.hpp'. I know it's not the right way to implemente operators, but with the other ways also got errors. Thanks.
EDIT:
forgot to mention, the error is: passing ‘const Paciente’ as ‘this’ argument discards qualifiers [-fpermissive]
bool operator==(const Paciente& p1, const Paciente& p2)
This has two constant objects as parameters.
However,
const string & getNombre(){return nombre_;};
is not a constant method and thus not allowed to be called on a constant object, which is what you try to do with p1.getNombre().
Simply change it to
const string& getNombre() const { return nombre_; }.
To elaborate a bit more on that, since you wrote "but when calling (const) getters of that class": A method is exactly const if you declare it as such, as I did. Simply it semantically not changing the object is not enough. The compiler is not "clever" enough to check semantics, and it really shouldn't be, easy source for errors.
Also note that it returning a const string& does not make the method const. Simply think of a signature like
const string& iterate_one_step_and_return_status_string();
(yes, this is horrible long name one should not use).
By the way, the semicolons at the end of your method implementations do nothing. You need those only when you only declare but not implement.
Also, I'd recommend to use english for everything but values. In this case, it is not that important, but should you post code for which us understanding what you want to do is important, it is helpful if we can get to know that by the names.
Edit: another problem with your code I noticed:
string setNombre(const string &nombre){nombre_ = nombre;};
This method has return type string yet does not return anything. I actually wonder why your compiler hasn't given you a warning or error like Error: control may reach end of non-void function.
(This also applies to your other setters.)
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
In my header file I declare structure
typedef struct _PreprocessedImage
{
cv::Rect straight;
cv::Rect diagonal;
bool empty = true;
...
...
} PreprocessedImage;
Then I create class with method
std::vector<float> processData(cv::Mat &image, bool drawRegions = false, PreprocessedImage &preproc);
.
Try to compile and got
"error: default argument missing for parameter 3"
But when I try to declare method with default value, like that:
std::vector<float> processData(cv::Mat &image, bool drawRegions = false, PreprocessedImage &preproc = PreprocessedImage());
.
I got
"error: invalid initialization of non-const reference of type
'PreprocessedImage& {aka _PreprocessedImage&}' from an rvalue of type
'PreprocessedImage {aka _PreprocessedImage}'"
How can i fix it?
All parameters with defaults should be at the end of the list, so you need something like:
std::vector<float> processData(cv::Mat &image, PreprocessedImage &preproc, bool drawRegions = false);
.
To add to paxdiablo's answer.
Yes, the default-argument parameters must come last. Your attempt to work around this by also giving preproc a default argument failed because a temporary cannot bind to an lvalue reference (it would have to be const); besides, giving something a default "for the sake of it" is probably not what you wanted to do.
An alternative, that doesn't require re-arranging your existing function, is to write a forwarding overload instead of using default arguments:
std::vector<float> processData(cv::Mat& image, bool drawRegions, PreprocessedImage& preproc)
{
/* ... */
}
std::vector<float> processData(cv::Mat& image, PreprocessedImage& preproc)
{
return processData(image, false, preproc);
}
By the way, you don't need (or want) that antique C-style typedef struct A { ... } B syntax in C++ (unless you require direct C compatibility); you just want struct B. And, if you really must go for the former, you should pick a name that isn't reserved to the implementation.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
This may be a trivial question for most but I am new to c++. My question is, how would I pass a pointer which is deference to a function to operate on the pointed value?
char first_name[] = "hello";
int myFunc(const char *source){
innerFunc(char *source){/*append world*/}
}
This doesnt seem to work.
One example:
char first_name[] = "hello";
int inner_func(const char* source) { /* do something, read-only */ }
int my_func(const char* source) {
inner_func(source);
}
So, you merely need to pass the name, that's all.
However, note that you have passed the pointer as const, which means that you cannot change it. Appending world does not work in that instance. In fact, if you would like to operate on your char string in a changing manner, you would need to create a second char* dynamically with the extended size. You cannot change source.
Also, inner functions like that cannot be defined in C++. Just define it outside of myFunc. You can create inner functions with lambdas, but this would be another answer.
Luckily, in C++, manipulating strings is far easier and deeply to recommend:
#include <string>
std::string first_name = "hello";
int inner_func(std::string& source) {
source += " world";
}
int my_func(std::string& source) {
inner_func(source);
}
Now, when you pass a string like first_name to my_func, it will be passed to inner_func where some string is appended.
Note, though, that hello world is quite a strange name, especially as a first name. It might not be what you want.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Ok I have used C for 3 years.
My major is embedded system Engineering
I have had an interest in image processing just a few days ago.
So I am studying C++.
I want to change last character when I use copy constructor.
like these -> Cannon1 Cannon2 Cannon3 (Cannon is just name)
So I used pointer with While as I do in C.
Photon_Cannon::Photon_Cannon(int x, int y, char *cannon_name)
{
int i = 0;
hp = shield = 100;
coord_x = x;
coord_y = y;
damage = 20;
name = new char[strlen(cannon_name) + 1];
strcpy(name, cannon_name);
}
this is original code (this works normally)
and I attached some codes end of the section of copy constructor.
while (*name!=NULL) {
name++;
}
*name+=1;
but it doesn't work! :(
help me...
Try to use std::string instead of char*.
Photon_Cannon::Photon_Cannon(int x, int y, const std::string& cannon_name)
Change member variable name to std::string aswell, then you can easily assign string's like
name = cannon_name;
And then change last character
name[name.length() - 1] = '2';
Or
name.pop_back();
name += "2";
Don't forget to include string.
Or with char*
name[strlen(name) - 1] = '2';
Dont forget to check size of array/string, name.length() > 0), (int)strlen(name) > 1, ...
I would recommend you to read some c++ tutorial's like
C++ strings.
Iam new on stackoverflow, so i hope it helped you :).
This is not intended as answer, just as a side note to Filip's already given answer (and the comments there):
void f(std::string const& s)
This is the usual way to pass std::string objects, because it avoids creating unnecessary copies of (costing runtime and memory). If you actually want to modify the string (changes will be visible to the string object passed to f), leave away the const modifier.
Now here we have a special case:
void f(std::string const& s)
{
std::string ss(s); // creates a COPY!
// modify the copy ss...
}
Obviously, the copy is to be modified, but changes shall not be visible to the original string object passed to. If we don't need access to the original string any more (s), then and only then, it makes sense to pass the string by value:
void f(std::string /*const&*/ s) // creates the COPY already when passing
{
/* std::string ss(s); // creates a COPY! */ // <- don't need it any more
// modify the COPY s now...
}
Side note: Really leaving the const reference as comment as above (/*const&*/) would express (and should suffice for) that passing by value was done intentionally...
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I was making a simple C++ program using CTable - my custom class. CTable contains a pointer to an array of int, which can be resized and manipulated with CTable methods.
Here's a short snippet:
class CTable
{
private:
int *table; //pointer to the table
int length; //length of the table
///...etc
public:
int SetLength(int length); //returns -1 on failure
int SetValueAt(int index, int value); //returns -1 on failure
///...etc
CTable& operator+=(CTable &other) //combine 2 CTables together
{
int oldLength = length;
SetLength(length+other.GetLength());
for(int i=oldLength;i<length;i++)
{
SetValueAt(i,other.GetValueAt(i-oldLength));
}
return *this;
}
};
I also have another function that I use to split user input into words:
vector<string>* splitString(string sentence, char delim)
{
vector<string> *res = new vector<string>();
stringstream ss;
ss.str(sentence);
string word;
while (getline(ss,word,delim))
{
res->push_back(word);
}
return res;
}
It is important to note that all the methods presented here seem to work fine on their own, i.e. when I test them individually.
As you can see I have also overloaded the += operator. The problem is that whenever I use this operator, the next user input crashes the program when the splitString() function is called. The program crashes with the sole error message "terminate called recursively". No exceptions is thrown, nothing. Only an error code 0xC0000005
I can't really show you the entire code because the program got pretty big, currently about 1000 lines of code. I try to fix this program for hours and I have no idea what's going on. Any help is greatly appreciated !
The windows error code 0xC0000005 means STATUS_ACCESS_VIOLATION. This is typically caused by problem with pointers, out of bound array accesses, memory corruption and other serious issues.
The splitString() function looks ok, so it certainly not causes by itself the kind of behavior you're describing.
The operator+=() looks more suspicious. The code itself seems ok, but it makes assumptions that SetLength() changes the length, reallocates the pointer, and copies all the existing values, all without any problem. Note by the way that this code doesn't handle special case such as doing += on one self.
Unfortunately, the signature of this function is int SetLength(int length);. So the name of the parameter hides the name of the member length, which could cause some serious mismatches that could lead to buffer overflows or unchanged member length (unless you use this->length and length to make the difference between the two).
Finally, you are using raw pointers instead of smart pointers. So you must ensure the rule of 3. If you don't, you will end-up with shallow copies which could also lead to UB (when one of the object releases the memory that it's copy is still using).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
If I declare a function:
vector<int> & call(string *target)
How should I use target in the function for a comparison with another string? For example:
string str;
if(str == //string in target){
...
}
As &target, or simply target? Also, how should the return look? I'm assuming it should be:
return &some_vector;
since that is the type in the function declaration. Finally, what about the opposite? That is:
vector<int> & call(string &target)
When in the function and wanting to use the string, is it as simple as:
*target
On your first question it's
if(str == *target){
On your second question my advice would simply be, don't. It looks like you are trying to return a reference to a local variable. That is a well known newbie mistake that will simply crash your program.
On your third question it's
if(str == target){
You need to dereference the pointer to get the object. That is, use *:
if (str == *target) {
Also, how should the return look?
You're returning a reference, not a pointer. That means you simply need to return the name of the object:
return some_vector;
Finally, what about the opposite?
If target is a reference (NOT a pointer) than you simply use the name of the object. There's no dereference involved with this.