Answers for "operator syntax c++"

C++
4

c++ .* operator

The .* operator is used to dereference pointers to class members.
Posted by: Guest on September-03-2020
2

c++ overloaded == operator

#include <iostream>
#include <string>
 
class Car
{
private:
    std::string m_make;
    std::string m_model;
 
public:
    Car(const std::string& make, const std::string& model)
        : m_make{ make }, m_model{ model }
    {
    }
 
    friend bool operator== (const Car &c1, const Car &c2);
    friend bool operator!= (const Car &c1, const Car &c2);
};
 
bool operator== (const Car &c1, const Car &c2)
{
    return (c1.m_make== c2.m_make &&
            c1.m_model== c2.m_model);
}
 
bool operator!= (const Car &c1, const Car &c2)
{
    return !(c1== c2);
}
 
int main()
{
    Car corolla{ "Toyota", "Corolla" };
    Car camry{ "Toyota", "Camry" };
 
    if (corolla == camry)
        std::cout << "a Corolla and Camry are the same.n";
 
    if (corolla != camry)
        std::cout << "a Corolla and Camry are not the same.n";
 
    return 0;
}
Posted by: Guest on June-17-2020
0

operators c++

// Operators are simply functions but cooler
// E.g: The + sign is an operator, [] is an operator, you get the point
// Which is even cooler is you can overload them
// Means you can change their behavior
// I can make + actually decrement (dont do this)
int operator+(int other){
	return *this - other;
}
// And make - return always 0
int operator-(int other){ return 0; }
// (THIS IS ANOTHER PROGRAM SO + AND - ARE NOT BROKEN ANYMORE)
#include <iostream>
#include <string>
#include <stdio.h>
#include <vector>
// And then im gonna make a class
class UselessClass{
private:
  	// And have a vector of integers with a bunch of numbers
  	std::vector<int> numbers = {1, 2, 3};
public:
  	// Then im gonna make the array index operator return the int at the index but with 5 added to the int
  	int operator[](int index){
    	return this->numbers[index] + 5;
    }
};
int main(){
    // And then
    UselessClass a;
    std::cout << a[0] << "n";
    // It will print 6
}
Posted by: Guest on July-23-2021

Browse Popular Code Answers by Language