0

I have a class:

class taphop
{
    public:
        taphop();
        ~taphop();   
        taphop(const list&);
        taphop& operator=(const taphop&);
        taphop operator+(const int&);
        taphop operator+(const taphop&);
};

In main, I can't using multiple parameters:

main()
{
     taphop lmc=lmc+2+5+3+2; // Error;
     lmc=lmc+3+5+2; // Error;
     int a=a+1+2+4+5;   // Not error;
     a=a+1+2+4+5;   // Not error;
     return 0;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 5
    `taphop lmc=lmc+2+5+3+2;` This is undefined behavior. How can you assign a variable to itself it if has not yet be assigned a value? – Cory Kramer Nov 13 '14 at 12:42
  • 2
    When posting questions about errors, please include the complete and unedited error output in the question. – Some programmer dude Nov 13 '14 at 12:43
  • Please paste the error as well as implementation of your operators... – ravi Nov 13 '14 at 12:44
  • @Alex: Reference to what object? BTW: `operator+` should be `const`. Also, implicit int in C++?? – Deduplicator Nov 13 '14 at 12:44
  • implement `+=` first http://stackoverflow.com/questions/4421706/operator-overloading http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html – phuclv Nov 13 '14 at 12:46
  • 2
    @AlexFarber No, the arithmetic operators creates a copy and return that, assignment (for example) returns a reference to itself (as does the arithmetic assignment operators). – Some programmer dude Nov 13 '14 at 12:46
  • Did you forget to link with the implementations of those functions? – molbdnilo Nov 13 '14 at 12:50
  • 1
    [Works for me](http://ideone.com/G0LOWA), apart from link errors since I didn't define the member functions, once I added the missing return type to `main`. Please post the errors, with enough code to reproduce them. – Mike Seymour Nov 13 '14 at 12:56

2 Answers2

0

One thing for sure. Below is undefined.

taphop lmc=lmc+2+5+3+2;

As operator+ would be called on the carcass of supposed-to-be-fully-constructed object in expression

lmc+2+5+3+2
ravi
  • 10,994
  • 1
  • 18
  • 36
0

In addition to using lmc to initialize lmc, you just need to read the error messages the compiler is giving you. Here is my take on what you might be trying to do:

class taphop
{
    int value;
public:
    taphop(const int x = 0) :value(x) {} // default value of 0
    ~taphop() {}
    int getvalue() const { return value; }
    taphop& operator=(const taphop &r) { value = r.value; return *this; }
    taphop operator+(const int x) { return taphop(value + x); }
    taphop operator+(const taphop &r) { return taphop(value + r.value); }
};

int main()
{
    taphop lmc = taphop(0) + 2 + 5 + 3 + 2;
    std::cout << lmc.getvalue() << std::endl; // prints 12
    lmc = lmc + 3 + 5 + 2;
    std::cout << lmc.getvalue() << std::endl; // prints 22
    return 0;
}
Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30