Write a copy assignment operator for CarCounter that assigns objToCopy.carCount to the new objects's carCount, then returns *this. Sample output for the given program:

Respuesta :

Answer:

Here is the copy assignment operator for CarCounter:

CarCounter& CarCounter::operator=(const CarCounter& objToCopy) {

carCount = objToCopy.carCount;

return *this;  }

The syntax for copy assignment operator is:

ClassName& ClassName :: operator= ( ClassName& object_name)

In the above chunk of code class name Is CarCounter and object name is objToCopy.

Assignment operator = is called which assigns objToCopy.carCount to the new objects's carCount.

This operator basically is called when an object which is already initialized is assigned a new value from another current object.

Then return *this returns the reference to the calling object

Explanation:

The complete program is:

#include <iostream>  //to use input output functions

using namespace std;   //to access objects like cin cout

class CarCounter {  //class name

public:  // public member functions of class CarCounter

CarCounter();  //constructor of CarCounter

CarCounter& operator=(const CarCounter& objToCopy);  //copy assignment operator for CarCounter

void SetCarCount(const int setVal) {  //mutator method to set the car count value

carCount = setVal;  } //set carCount so setVal

int GetCarCount() const {  //accessor method to get carCount

return carCount;  }  

private:  //private data member of class

int carCount;  };    // private data field of CarCounter

CarCounter::CarCounter() {  //constructor

carCount = 0;  //intializes the value of carCount in constructor

return; }  

// FIXME write copy assignment operator  

CarCounter& CarCounter::operator=(const CarCounter& objToCopy){

/* copy assignment operator for CarCounter that assigns objToCopy.carCount to the new objects's carCount, then returns *this */

carCount = objToCopy.carCount;

return *this;}  

int main() {  //start of main() function

CarCounter frontParkingLot;  // creates CarCounter object

CarCounter backParkingLot;   // creates CarCounter object

frontParkingLot.SetCarCount(12);  // calls SetCarCount method using object frontParkingLot to set the value of carCount to 12

backParkingLot = frontParkingLot;  //assigns value of frontParkingLot to backParkingLot

cout << "Cars counted: " << backParkingLot.GetCarCount();  //calls accessor GetCarCount method to get the value of carCount and display it in output

return 0;  }

The output of this program is:

Cars counted = 12

Ver imagen mahamnasir
ACCESS MORE
ACCESS MORE
ACCESS MORE
ACCESS MORE