[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Overload operator+ in c++ with wxWindows

Posted on 2006-03-28
48
Medium Priority
?
775 Views
Last Modified: 2012-05-05
[i'm sorry for my English]

Hi!
I really need to solve my problem in few hours... it's very important for me!!!
Please... help me!!! i hope u can help me...

My code is in c++ and i used wxwidgets to make my prog run in a frame/window dialog...
I use dev-cpp with all libreries... and when i compile my code i have no errors, my code works great... but i have a great problem.
I use three text control to do some math operation:

First wxTextCtrl is named wxEdit1.
Second wxTextCtrl is named wxEdit2.
Third wxTextCtrl is named wxEdit3.

1. I convert the content of the first two wxTextCtrl to int or float
2. I add the content of wxEdit1 to wxEdit2 (wxEdit1 + wxEdit2)
3. I display the correct result in wxEdit3

i use template to manage different kind of data.

This is a screenshot of the situation:
http://lnx.mangaitalia.net/question1.gif

the code i wrote is this:

[code]
class MyStringClass: public wxString
{
public:
        template <class T> bool From_String(T &aValue, const std::string &aStr);
        template <class T> std::string To_String(T aValue);  
        MyStringClass &operator + (const MyStringClass &o);
};


template <class T>
bool MyStringClass::From_String(T &aValue, const std::string &aStr)
{  
   std::stringstream string(aStr);                                          
   return string >> aValue;        
}

template <class T>
std::string MyStringClass::To_String(T aValue)
{
   std::stringstream string;
   string << aValue;          
   return string.str();
}
[/code]

and i add the values with:

[code]
void Frame::OnButtonAdd(wxCommandEvent& WXUNUSED(event))
{
   std::string numero1;
   std::string numero2;  
   
   MyStringClass var;
   
   //uso il template per gestire le stringhe e convertirle in interi o float!
   
   num1 = wxEdit1->GetValue();
 
   num2 = wxEdit2->GetValue();
     
 
   if(var.From_String(b, num1) && var.From_String(c, num2)) {                                                  
      std::string res = var.To_String((b + c));
      wxEdit3->SetValue(res.c_str());
   }
   ...
   ...
   ...
[/code]

Now... i need to overload the operator+ in order to add "+2" everytime my code try to add wxEdit1+wxEdit2 or to do others sums.
Here is an example:

wxEdit1 = 4;
wxEdit2 = 8;

the sum must to be: wxEdit1 + wxEdit2 + 2 = 4 + 8 + 2 = 14

i must to do this by using the overload of operator+.

i tried to do this:

[code]
MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
      const std::string string;
      MyStringClass hope;
      std::string hope_work(o);
     
      // hope_work << o;
 
  double b,c;
 
  if(hope.From_String(b, string) && hope.From_String(c, hope_work))
   {                                                    
      std::string res1= hope.To_String((string + hope_work)+2);
   }
 
return *this;
}
[/code]

Dev-Cpp gives me no errors, but the overload doesn't work because i don't know what excatly write to overload the operator and i don't know what value to return to make it wroks well...

Can u help me, please?
i really need to solve this problem in few hours...
please...


Thanks for All!
0
Comment
Question by:roccogalati
  • 23
  • 12
  • 9
  • +1
45 Comments
 
LVL 48

Expert Comment

by:AlexFM
ID: 16310460
Can you show client code which should use operator+ ? If you want to add 2, you need operator+(int).
0
 
LVL 30

Expert Comment

by:Axter
ID: 16310463
Hi roccogalati,
> Dev-Cpp gives me no errors, but the overload doesn't work because i
> don't know what excatly write to overload the operator and i don't know
> what value to return to make it wroks well...
Can you please give us more details on how it doesn't work?
What doesn't it do, and what are you expecting it to do?

David Maisonave (Axter)
Cheers!
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16310527
Try

MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
     int a, b;
     if (From_String(a, *this) && From_String(b, o))
          return To_String(a+b).c_str();
     return "";      
}

To add the +2 you might use another overload

MyStringClass &MyStringClass::operator + (int b)
{
     int a;
     if (From_String(a, *this))
          return To_String(a+b).c_str();
     return "";      
}

You should be able to use it like

      std::string res = var.To_String((b + c + 2));
      wxEdit3->SetValue(res.c_str());


Note, normally operator+ would concatinate strings rather than convert them to integers and add them.

Note, you shouldn't have to use std::string as type "between". Actually, if your MyStringClass could be converted to const char* and vice versa you don't need std::string.

Regards, Alex
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 30

Expert Comment

by:Axter
ID: 16310570
The following is the recommended approach to overloading arithmetic and assignment operators:

T& T::operator+=(const T&){
//.... impl
 return *this
}

T operator+(const T& lhs, const T& rhs){
 T temp(lhs);
 return temp += rhs;
}
0
 
LVL 30

Expert Comment

by:Axter
ID: 16310641
Notice in my above example, that operator+() function is not a member, and instead it's a global function.
I recommend you make these functions inline functions and declare and implement them within your MyStringClass class declaration.
Example

class MyStringClass
{
 ///.... impl
publicL:
     template<class T>
     MyStringClass& operator+=(const T& src){
        *this = To_String(*this) + To_String(src);
         return *this
     }  
};
0
 
LVL 30

Expert Comment

by:Axter
ID: 16310679
Here's example for operator+()

The following would be declared outside of your MyStringClass class declaration, and it would not be a member, and instead a global function.

template<class T>
MyStringClass operator+(const MyStringClass& lhs, const T& rhs){
 MyStringClass temp(lhs);
 return temp += T;
}
0
 

Author Comment

by:roccogalati
ID: 16310712
Sorry Axter!
i didn't know it is forbidden to post email adress... i'm sorry :(

I'll try to explain better the problem.


this is the class frame where wxedit1, wxedit2 and wxedit3 are initialized:

######################################

class Frame : public wxFrame
{
      private:
      DECLARE_EVENT_TABLE();
      
         public:
            Frame(wxWindow *parent, wxWindowID id = 1, const wxString &title = wxT("Project1"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = Frame_Principale_STYLE);
            virtual ~Frame_Principale();
            
      public:
            //Do not add custom control declarations
            //wxDev-C++ will remove them. Add custom code after the block.
            ////GUI Control Declaration Start
            wxTextCtrl *wxedit1;
            wxTextCtrl *wxedit2;
                                wxTextCtrl *wxedit3;
            wxButton *sum; // when sum is pressed ii add wxedit1 to wxedit2 and show the result to wxedit3
            ////GUI Control Declaration End
            
      public:
            //Note: if you receive any error with these enum IDs, then you need to
            //change your old form code that are based on the #define control IDs.
            //#defines may replace a numeric value for the enum names.
            //Try copy and pasting the below block in your old form header files.
            
            
      public:       
            void OnButtonAdd(wxCommandEvent& event); // this function add wxedit1 to wxedit2 and show the result in wxedit3
                     
};

###############################


This is the class i used to overload the operator+ and to do the sum:

###############

class MyStringClass: public wxString
{
public:
        template <class T> bool From_String(T &aValue, const std::string &aStr);
        template <class T> std::string To_String(T aValue);  
        MyStringClass &operator + (const MyStringClass &o);  // this is the prototype of the operator+
};


// this function use template to manage different kind of data: int, float, double, etc...
template <class T>
bool MyStringClass::From_String(T &aValue, const std::string &aStr)
{  
   std::stringstream stringa(aStr); // aStr = stringa_input, il costruttore stringstream fa una copia di aStr
                                         //  senza modificarlo a tutti gli effetti!
   return stringa >> aValue;        // legge il contenuto di aValue, se è un int, lo legge come un int
}

// this function use template to manage different kind of data
template <class T>
std::string MyStringClass::To_String(T aValue)
{
   std::stringstream stringa;
   stringa << aValue;          // salva in "stringa" il contenuto di "aValue"...
   return stringa.str();
}

##############################

Now, i do the sum with:

###############################

void Frame_Principale::OnButtonAdd(wxCommandEvent& WXUNUSED(event))
{
   std::string num1;
   std::string num2;  
   
   MyStringClass var;
   
     
   num1 = wxedit1->GetValue();
 
   num2 = exedit2->GetValue();
     
 
   if(var.From_String(b, num1) && var.From_String(c, num2))  // use template functions to manage different kind of data
   {                                                  
      std::string Res = var.To_String((b + c));  // is here where i would like to overload operator+! i'd like to sum (b+c+2) every time! not (b+c) !!!
      wxedit3->SetValue(Res.c_str());
   }
   else
   {
      wxMessageBox("Attenzione: conversione fallita!\n Inviare un resoconto dell'errore a rocco.g@libero.it");
   }  
               
}
###########################

i try to do the overload with this:

#########

MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
      const std::string string;
      MyStringClass hope;
      std::string hope_work(o);
     
      // hope_work << o;
 
  double b,c;
 
  if(hope.From_String(b, string) && hope.From_String(c, hope_work))
   {                                                    
      std::string risultato_operazione = hope.To_String((string + hope_work)+2);
   }
 
return *this;
}

#################

but i know it is not correct.

What i would do:

i want to overload the operator+ to add "+2"  every time i do a sum

for example:

when i do:
std::string Res = var.To_String((b + c));  

i would like to to this: Res = b + c + 2;

i know i can do simply:

std::string Res = var.To_String((b + c)+2);  

but i must use the overload of operator+ because i have to do others sums in other code parts...

i don't know if my prototype of the overload operator is correct...
i think it isn't for sure!

i don't know if i have to use operator+(int) or something else...

i know to do it in C++ without wxwidgets, but with wxwidgets i'm not able to understand how to do it...

i uploaded two files of my prog here:
http://lnx.mangaitalia.net/files.zip

if u need i can upload my entire project...
 
thanks to all, guys!
0
 
LVL 30

Accepted Solution

by:
Axter earned 1000 total points
ID: 16310781
>>std::string Res = var.To_String((b + c));  // is here where i would like to overload operator+! i'd like to sum (b+c+2) every time! not (b+c) !!!

What types are b and c

Did you try using the template functions I posted?

You should be able to do the following:

std::string Res = var.To_String(b) + var.To_String(c) + var.To_String(2) ;  
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16310855
You might consider to change your class to the following:

class MyStringClass: public wxString
{
public:
    template <class T> bool From_String(T &aValue)
    {
        istringstream iss((const char*)(*this));
        return iss >> aValue;
    }
    template <class T> MyStringClass& To_String(const T& aValue)
    {
        ostringstream oss;
        oss << aValue;
        *this = oss.str().c_str();
        return *this;
    }
    int To_Int(int errVal = -1)
    {
        int i;
        if (From_String(i))
        {
            return i;
        }
        return errVal;
    }
};

The To_String and From_String function operates on the *this string rather than on a string passed as an argument. With the To_Int function you might convert MyStringClass to integer rather than overloading operator+.

Regards, Alex
0
 

Author Comment

by:roccogalati
ID: 16310856
yes Axter!

i try to do this:

###############

class MyStringClass: public wxString
{
public:
        template <class T> bool From_String(T &aValue, const std::string &aStr);
        template <class T> std::string To_String(T aValue);  
        template<class T>
         MyStringClass& operator+=(const T& src){
        *this = To_String(*this) + To_String(src)+ To_String(2);
         return *this;
     };  
 
};

################

the problem is that i don't want to add "+2" in this function:

############
if(var.From_String(b, num1) && var.From_String(c, num2))
   {                                                  
      std::string Res = var.To_String((b + c));
      wxedit3->SetValue(Res.c_str());
   }
###############

i would like to add "+2" inside the overload function...

if i want to add "+2" inside onButtonAdd function i can simply do this:

std::string Res = var.To_String((b + c)+2);
and it works well...

but i would like to add "+2" inside the overload and to return  "value +2"...

i know i'm not very clear... :(
i'm sorry...

i hope u have understood this time... :(

 
0
 

Author Comment

by:roccogalati
ID: 16310908
thanks for ur answer itsmeandnobodyelse!

but the problem is that i have to use operator+... :(

if u need my entire project i can upload it... without problems...
0
 
LVL 30

Expert Comment

by:Axter
ID: 16310927
>>std::string Res = var.To_String((b + c)+2);

Again, what type is b and what type is c?
0
 

Author Comment

by:roccogalati
ID: 16310962
sorry!
i forget to give u this information! :(

b and c are declared in the Frame class, like this:

####
class Frame_Principale : public wxFrame
{
      private:
            DECLARE_EVENT_TABLE();
      
          //std::string numero1;
        //std::string numero2;  
        double b, c;

#####
0
 
LVL 30

Expert Comment

by:Axter
ID: 16311032
>>but i would like to add "+2" inside the overload and to return  "value +2"...

Exactly where do you want to add this "+2" string?

If you're trying to add a "+2" string to a double, you're going to need a convertions function.  This is not realy related to the operator+() function.

You're going to need a convertions function that will check the first character to see if it's negative or possitive, and then do a atof on the remainder of the string.
Then return that value with a plus or minus depending on the first character.
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16311095
Try

MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
     int a, b;
     if (From_String(a, *this) && From_String(b, o))
          return To_String(a+b+2).c_str();  // Here I added +2
     return "";      
}

Regards, Alex
0
 

Author Comment

by:roccogalati
ID: 16311118
mmh...
i'm thinking about a thing:

if i use this:


#######

class MyStringClass: public wxString
{
public:
        template <class T> bool From_String(T &aValue, const std::string &aStr);
        template <class T> std::string To_String(T aValue);  
        template<class T>
         MyStringClass& operator+=(const T& src){
        *this = To_String(*this) + To_String(src)+ To_String(2);
         return *this;
     };  
 
};

####

and then i do the sum with this:

std::string Res = var.To_String(b) + var.To_String(c) + var.To_String(2);

i'm only concatenate three strings, in fact the result displayed in wxedit3 is bc2;
so for example if i type:

wxedit1 ->4
wxedit2 ->5

i have in wxedit3-> 452

but i have to do a maths sum:
wxedit1->4
wxedit2->5
result in wxedit3 -> (9+2) = 11;


0
 

Author Comment

by:roccogalati
ID: 16311168
if i use ur code, alex..

wxdevcpp gives me some errors:

roject1Frm.cpp: In member function `MyStringClass& MyStringClass::operator+(const MyStringClass&)':
Project1Frm.cpp:165: error: no matching function for call to `MyStringClass::From_String(int&, MyStringClass&)'
Project1Frm.h:144: note: candidates are: bool MyStringClass::From_String(T&, const std::string&) [with T = int]
Project1Frm.cpp:165: error: no matching function for call to `MyStringClass::From_String(int&, const MyStringClass&)'
Project1Frm.h:144: note: candidates are: bool MyStringClass::From_String(T&, const std::string&) [with T = int]

Project1Frm.cpp:166: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'
Project1Frm.cpp:167: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'

make.exe: *** [Project1Frm.obj] Error 1

Execution terminated


i tried yersterday to do something like that... and it showed me the same errors... :(
0
 
LVL 30

Expert Comment

by:Axter
ID: 16311179
>>but i have to do a maths sum:

To do the math, you need to convert to double, and not to a string.
When the math is complete, then you convert to string.
0
 

Author Comment

by:roccogalati
ID: 16311224
mmh...
Axter...

but my code works well, it already do a math sum without problems!

i just need to do that overload in order to add "+2" to a and b each time i do a sum...


i uploaded u the .exe of my program... so u can understand like it run...

http://lnx.mangaitalia.net/Project1.zip
0
 

Author Comment

by:roccogalati
ID: 16311248
i uploaded also the entire source for wxdevcpp:
http://lnx.mangaitalia.net/source.zip

sorry guys... :(
i'll be back in 2 hours... :(
0
 
LVL 30

Expert Comment

by:Axter
ID: 16311324
>>i just need to do that overload in order to add "+2" to a and b each time i do a sum...

Please post a good example, showning exactly what you're trying to do, and please exclude all the types.
0
 

Author Comment

by:roccogalati
ID: 16312798
i write u a code in c++ to show u what i want to do:

###
#include <iostream>
using namespace std;

class Sum {

public:
    Sum(int num = 0)
    {
        this->num = num;
       
    }
   
    Sum operator+(const int i)
    {
        Sum temp;
        temp.num = this->num + i + 2;
        return temp;  
    }
    void print()
    {
        cout << num;
    }
private:
   
    int num;
   
};
int main() {
   
    Sum a(1);    
    int b = 5;
    Sum c;

    c = a + b;  // c = a + b + 2 !!!
    c.print();

    return 0;
}
###

in this code i write, we have this situation:

a = 1
b = 5

when i do the sum and save the result in c
i dont have c = a + b = 6
but i have:
c = 8 because it sum a + b + 2 = 8;

in this code, i overloaded operator+ to add "+2" each time i do a sum.

I would like to do the same thing in the code i show u before...


i hope this time i've been very clear... :)


i don't have to concatenate strings...
i have to do math... and my prog without the overload already do correct operations, but i need to add "+2" each time i do a sum, like in the previuos code...

0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16313348
>>>> error: no matching function for call to `MyStringClass::From_String(int&, MyStringClass&)'

Unfortunately, I don't know the wxString member function that turns a 'wxString' to a 'const char*' .

You might try to cast:

       ...
       if (From_String(a, (const char*)(*this)) && From_String(b, (const char*)o))

       ...

If that doesn't work you might post the header of wxString class.

Regards, Alex


0
 

Author Comment

by:roccogalati
ID: 16313452
if i do this:

MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
     int a, b;
     if (From_String(a, (const char*)(*this)) && From_String(b, (const char*)o))
          return To_String(a+b+2).c_str();  // Here I added +2
     return "";      
}


it says me:

MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
     int a, b;
     if (From_String(a, (const char*)(*this)) && From_String(b, (const char*)o))
          return To_String(a+b+2).c_str();  // Here I added +2
     return "";      
}



this is the wxstring reference:
http://www.wxwindows.org/manuals/2.6.1/wx_wxstring.html#wxstringconstruct

and this is the include file string.h:
http://lnx.mangaitalia.net/string.h

 
0
 

Author Comment

by:roccogalati
ID: 16314251
i did a mistake in my previous post!

when i compile it, devcpp says me:

Project1Frm.cpp: In member function `MyStringClass& MyStringClass::operator+(const MyStringClass&)':
Project1Frm.cpp:166: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'
Project1Frm.cpp:167: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'

make.exe: *** [Project1Frm.obj] Error 1

Execution terminated
0
 

Author Comment

by:roccogalati
ID: 16316035
I think that itsmeandnobdoyelse has understood what i want to do...

in any case...

i report again my post where i try to explain the problem better:

[quote from my previous post]

i write u a code in c++ to show u what i want to do:

###
#include <iostream>
using namespace std;

class Sum {

public:
    Sum(int num = 0)
    {
        this->num = num;
       
    }
   
    Sum operator+(const int i)
    {
        Sum temp;
        temp.num = this->num + i + 2;
        return temp;  
    }
    void print()
    {
        cout << num;
    }
private:
   
    int num;
   
};
int main() {
   
    Sum a(1);    
    int b = 5;
    Sum c;

    c = a + b;  // c = a + b + 2 !!!
    c.print();

    return 0;
}
###

in this code i write, we have this situation:

a = 1
b = 5

when i do the sum and save the result in c
i dont have c = a + b = 6
but i have:
c = 8 because it sum a + b + 2 = 8;

in this code, i overloaded operator+ to add "+2" each time i do a sum.

I would like to do the same thing in the code i show u before...


i hope this time i've been very clear... :)


i don't have to concatenate strings...
i have to do math... and my prog without the overload already do correct operations, but i need to add "+2" each time i do a sum, like in the previuos code...

[/quote]

0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16318475
It seems from wxstring.h that wxString has a member function c_str (same as std::string) that returns a 'const char*' from a wxString string. As MyStringClass is derived from wxString and std::string takes a const char* the following code should compile

MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
     int a, b;
     if (From_String(a, c_str()) && From_String(b, o.c_str()))
          return To_String(a+b+2).c_str();  // Here I added +2
     return "";      
}

Regards, Alex

0
 

Author Comment

by:roccogalati
ID: 16319855
i tried to do something like this yesterday night...

but i don't compile...

####
MyStringClass &MyStringClass::operator + (const MyStringClass &o)
{
     int a, b;
     if (From_String(a, c_str()) && From_String(b, o.c_str()))
          return To_String(a+b+2).c_str();  // Here I added +2
     return "";      
}
###


give me these errors:

Project1Frm.cpp: In member function `MyStringClass& MyStringClass::operator+(const MyStringClass&)':
Project1Frm.cpp:166: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'
Project1Frm.cpp:167: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'

make.exe: *** [Project1Frm.obj] Error 1

Execution terminated

166:     return To_String(a+b+2).c_str();  // Here I added +2
167:     return "";
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16320021
>>>> error: invalid initialization of non-const reference of
>>>> type 'MyStringClass&' from a temporary of type 'const char*'

I don't know the message but you may have to make the operator function const to get it compiled. That should work as there is no change to the current string object.

Add the 'const' keyword to the prototype and the implementation:

class MyStringClass : public wxString
{
    ...
    MyStringClass &operator + (const MyStringClass &o) const;
};


 MyStringClass & MyStringClass::operator + (const MyStringClass &o) const
 {
     ...
 }

BTW, if that compiles you might go back to a previous version as it was always the same error.

Regards, Alex
0
 

Author Comment

by:roccogalati
ID: 16320044
mmmh...

others errors:

Project1Frm.cpp: In member function `MyStringClass& MyStringClass::operator+(const MyStringClass&) const':
Project1Frm.cpp:165: error: passing `const MyStringClass' as `this' argument of `bool MyStringClass::From_String(T&, const std::string&) [with T = int]' discards qualifiers
Project1Frm.cpp:165: error: passing `const MyStringClass' as `this' argument of `bool MyStringClass::From_String(T&, const std::string&) [with T = int]' discards qualifiers
Project1Frm.cpp:166: error: passing `const MyStringClass' as `this' argument of `std::string MyStringClass::To_String(T) [with T = int]' discards qualifiers
Project1Frm.cpp:166: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'
Project1Frm.cpp:167: error: invalid initialization of non-const reference of type 'MyStringClass&' from a temporary of type 'const char*'

make.exe: *** [Project1Frm.obj] Error 1

Execution terminated


It may be i have to change the protoype without adding const?
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16320097
>>>> It may be i have to change the protoype without adding const?

No, but the From_String and To_String member functions need to be changed to 'const' as well cause you couldn't calll them from a 'const' member.

Regards, Alex


 
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16320164
>>>> MyStringClass&

I got it. You need to change the retun value to MyStringClass without '&' cause you can't return a reference to a temporay. So you have to return by value and not by reference.


Or you consider Axter's suggestion and change the operator+ to a (global) friend function taking two MyStringClass arguments:

class MyStringClass
{

   ...

   friend  MyStringClass operator + (const MyStringClass &sa, const MyStringClass &sb)
   {
     int a, b;
     MyStringClass t;  // a helper only
     if (t.From_String(a, sa.c_str()) && t.From_String(b, sb.c_str()))
          return t.To_String(a+b+2).c_str();  // Here I added +2
     return "";      
  }

};
0
 

Author Comment

by:roccogalati
ID: 16320213
i changed the return value to MyStringClass:

MyStringClass MyStringClass::operator + (const MyStringClass &o)  
{
     int a, b;
     if (From_String(a, c_str()) && From_String(b, o.c_str()))
          return To_String(a+b+2).c_str();  // Here I added +2
     return "";      
}

but it still gives me errors:

Project1Frm.cpp: In member function `MyStringClass MyStringClass::operator+(const MyStringClass&)':
Project1Frm.cpp:166: error: conversion from `const char*' to non-scalar type `MyStringClass' requested
Project1Frm.cpp:167: error: conversion from `const char*' to non-scalar type `MyStringClass' requested

make.exe: *** [Project1Frm.obj] Error 1

Execution terminated


it gives me the same errors if i consider Axter's suggestion...
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16320442
>>>> error: conversion from `const char*' to non-scalar type `MyStringClass' requested

Yes. You need to add an appropriate constructor to your class.

class MyStringClass : public wxString
{
     MyStringClass (const char* psz) : wxString(psz) {}
     ...
};

Regards, Alex
0
 

Author Comment

by:roccogalati
ID: 16320642
now...

it don't give me errors about operator+...

it gives me only an error in this function:

void Frame_Principale::OnButtonAdd(wxCommandEvent& WXUNUSED(event))
{
   std::string numero1;
   std::string numero2;  
   
   MyStringClass var;  // <- ERROR
   
   //uso il template per gestire le stringhe e convertirle in interi o float!
   
   numero1 = Lunghezza->GetValue(); // numero1 and numero2 are declared in teh previous class
 
   numero2 = Larghezza->GetValue();
     
 
   if(var.From_String(b, numero1) && var.From_String(c, numero2)) // passo a From_String la stringa caricata ed il double
   {                                                    // se la conversione è fattibile, procedo
      std::string risultato_operazione = var.To_String((b + c)); // To_String ritorna il corretto valore dell'operazione
      Risultato->SetValue(risultato_operazione.c_str()); // mostra il risultato nel form apposito
   }
   else
...
...
...


why i can't use anymore MyStringClass var to access to my class ?

it's because now with:

 MyStringClass (const char* psz) : wxString(psz) {}

i convert a wxstring into a const char* ?

0
 

Author Comment

by:roccogalati
ID: 16320836
it says me:

Project1Frm.cpp: In member function `void Frame_Principale::OnButtonAdd(wxCommandEvent&)':
Project1Frm.cpp:179: error: no matching function for call to `MyStringClass::MyStringClass()'
Project1Frm.cpp:165: note: candidates are: MyStringClass::MyStringClass(const MyStringClass&)
Project1Frm.h:141: note:                 MyStringClass::MyStringClass(const char*)

make.exe: *** [Project1Frm.obj] Error 1

Execution terminated
0
 

Author Comment

by:roccogalati
ID: 16321168
i think i have to change: MyStringClass var;

but why?

i tried different ways to call var, but i give always the same error...
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16322152
>>>> i think i have to change: MyStringClass var;

No, you only have to add a default constructor. As long as you had no constructor the compiler made a default constructor (no arguments) for you. But after adding the constructor that takes a const char* we need to add a default constructor as well:

class MyStringClass : public wxString
{
     MyStringClass() {}   // default constructor

     MyStringClass (const char* psz) : wxString(psz) {}
     ...
};


0
 

Author Comment

by:roccogalati
ID: 16324085
it compile without errors!

finally!

but even if:

is seems adding "+2" for real:
return To_String(a+b+2).c_str();  // Here I added +2

at the reality i do nothing...

the result is only the sum between a and b... :(

it's very strange!
code looks like to be good!
0
 
LVL 39

Assisted Solution

by:itsmeandnobodyelse
itsmeandnobodyelse earned 1000 total points
ID: 16324558
>>>> at the reality i do nothing...


Try

MyStringClass MyStringClass::operator + (const MyStringClass &o)  
{
     int a, b;
     
     if (!From_String(a, c_str()))
          return "";
     if (!From_String(b, o.c_str()))
          return "";
     int c = a + b + 2;

     std::string result = To_String(c);
     // MessageBox(NULL, result.c_str(), "", MB_OK);
     return result;
}

I hope you can debug. If not try to output the message box or put the result.c_str() into some edit field.

Regards, Alex

I am offline for some hours.





0
 

Author Comment

by:roccogalati
ID: 16324918
i tried to use message box...


it's very strange... but it seems that the prog never enter in overload function!!!

later i'll try to do the debug... i hope debug will give me more infos about the problem!

i'll post the results!
0
 

Author Comment

by:roccogalati
ID: 16324954
ah... i tried ur previous function...
it doesnt work...

Project1Frm.cpp: In member function `MyStringClass MyStringClass::operator+(const MyStringClass&)':
Project1Frm.cpp:174: error: conversion from `std::string' to non-scalar type `MyStringClass' requested

make.exe: *** [Project1Frm.obj] Error 1

Execution terminated



but now the problem is that it seems that the prog never enter in the overload function...

i'll try with debug... and let u now later...
0
 

Author Comment

by:roccogalati
ID: 16325407
nothing to report after the debug...


the only significant thing is that prog never enter in this function:

MyStringClass MyStringClass::operator + (const MyStringClass &o)  
{
     int a, b;
     if (From_String(a, c_str()) && From_String(b, o.c_str()))
          return To_String(a+b+2).c_str();  // Here I added +2
     return "";      
}
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 16329495
>>>> the only significant thing is that prog never enter in this function:

That means there is another operator+ function that does the job. Maybe the one Axter has recommended.
0
 

Author Comment

by:roccogalati
ID: 16334251
mmmh...

i think i'll find another why without doing the overload... it's too difficult...

:(


thanks a lot to all!!!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
Article by: evilrix
Looking for a way to avoid searching through large data sets for data that doesn't exist? A Bloom Filter might be what you need. This data structure is a probabilistic filter that allows you to avoid unnecessary searches when you know the data defin…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question