(C++) How to redefine "=" operator for object

166 views Asked by At

I have an object of class A.

class A[
{
   int x;
   string y;
   float z;
    ....
}

Then I have an int, called "integer". How can I redefine the = operator in order to do something like

int integer;
A obj = integer;

in order to obtain something equal to the constructor call with NOT all members:

A obj(integer,",0); 
1

There are 1 answers

0
Joseph Larson On

This is a little naughty, but:

#include <iostream>

using std::cout;
using std::endl;

class A {
public:
    int x;

    A & operator=(int value) {
        x = value;
        return *this;
    }
};

int main(int, char **) {
    A obj;

    obj.x = 5;
    cout << "Initially: " << obj.x << endl;

    obj = 10;
    cout << "After: " << obj.x << endl;

}

When run:

g++ Foo.cpp -o Foo && Foo
Initially: 5
After: 10

Is this what you're trying to do? Note that this is very naughty. class A is NOT an integer, and assigning it to an int is going to confuse people. C++ lets you do things that you probably shouldn't do, and this is one of them.