C++ :: How To Able To Overload A Multiplication Operator
Apr 24, 2014How would i be able to overload a multiplication operator that if, in the main example(0, 5, 0) * example (0, 5, 0) is given, it gives me 25?
View 1 RepliesHow would i be able to overload a multiplication operator that if, in the main example(0, 5, 0) * example (0, 5, 0) is given, it gives me 25?
View 1 RepliesI'm doing a refresher for C++ and have gotten to operator overloading. I'm trying to perform an operator overload with the insertion (<<) operator, but I have encountered a problem.
Here's my class [In a header file "Shinigami.h"]
#include<string>
namespace K{
class Quincy;
class Shinigami{
friend std::ostream& operator<<(std::ostream&, const Shinigami&);
[Code] .....
If the operator function is a friend of the 'Shinigami' class, why doesn't it recognize any of it's private members? I need it to be in this file because I'm doing a bit of association with the 'Quincy' class.
I thought it was the namespace, but I included that.
Here's my question. I'm coding a basic Linked List class (for the purpose of understanding and having fun, I know about STL), LList.
I have overloaded the [] operator so it returns the data of the index-th node in the list, for example, if I code
LList x;
....
cout<<x[5];
it prints the data of the 5th node in the list (for fun I decided to index from 1 to infinity).
My question: Now I want to be able to assign the value to the index-th node data, using [] and =, for example, I want to be able to write:
LList x;
.....
x[5] = 121;
How can I do that?
Say I have a class that requires dynamic allocation to implement a few of the operators. Take "+" for example; I need to create a new object to hold the sum of the two parameters whose size is not known at compile time.
I'm pretty sure the standard way to indicate a failure inside the overloading function would be to throw an exception. However I am currently involved in an embedded(ish) project where the spec. says no exceptions are to be used.
I think I have 2 options:
1. Return an "invalid" object (with a flag indicating an error has occurred) and check for this after each operation.
a = b + c
if (a.err)
// handle error
or
2. To forsake operator overloading entirely and think up a new way of doing things where all functions that involve dynamic allocation can return error codes. but this seems rather terrible too as I may end up with something like:
objA a
if (add(&a, b, c) == -1) // assuming b and c are initialized before this snippet starts
// handle error
Is there a number 3 that I haven't thought of? It seems that not allowing exceptions is fairly common even in the non-embedded world [URL] so how is this normally done? or is operator overloading usually avoided when exceptions are not allowed?
We're trying to overload the delete[] operator with specific arguments. Which is the right way to call it? We use the GNU compiler and obtain compiler errors with all of these samples:
#include<iostream>
using namespace std;
typedef unsigned int P;
[Code]....
I'm trying to come up with the union of two Vector ADT bags, so I have to overload the '+' operator, but I'm getting a bunch of error messages saying:
VectorBag.cpp: In instantiation of ‘VectorBag<ItemType> VectorBag<ItemType>::operator+(VectorBag<ItemType>) [with ItemType = int]’:
proj2.cpp:161:42: required from here
VectorBag.cpp:81:24: error: no match for ‘operator[]’ (operand types are ‘VectorBag<int>’ and ‘int’)
newBag.add(anotherBag[i]);
^
Here is the function to overload the operator:
template<class ItemType>
VectorBag<ItemType>
VectorBag<ItemType>::operator+(VectorBag<ItemType> anotherBag) {
VectorBag<ItemType> newBag;
for (int i = 0; i < anotherBag.getCurrentSize(); i++)
newBag.add(anotherBag[i]);
}
The add() function is pre-defined by me somewhere else in the code. It basically does push_back().
I want to overload prefix and postfix increment(++) operators with friend function. I also have to use the constructors for this. How can I do this? in C++
View 4 Replies View Relatedi am doing some practice problems and i can't seem to figure out how to do this. basically we have a students number of test scores, then the name followed by the scores they have in a text file. Then we have to make a class with a constructor, copy constructor, destructor, and overload the = operator and the input and output operator. Are we suppose to call the text file in the input overload operator?
Here is what i have so far.
This is my header file.
#ifndef STUDENTTESTSCORES_H
#define STUDENTTESTSCORES_H
#include <string>
#include <iostream>
using namespace std;
class StudentTestScores{
private:
string studentName;
[Code]...
i am 100% sure the overloading the input is wrong
here is the implementation of the constructor copy constructor and desctructor
#include <iostream>
#include "StudentTestScores.h"
using namespace std;
StudentTestScores::StudentTestScores(string name = "", int numScores = 0)
{
studentName = name;
numTestScores = numScores;
if (numScores <= 0)
testScores = NULL;
else
[Code]...
and here is the notepad file
3
Justin Bieber491.469.184.681.081.5
Miley Cyrus380.080.090.083.3
Kim K490.575.661.481.677.2
The program is suppose to use all the information and read from the notepad and output the exact things as the notepad file
struct Node {
int entry;
Node *next;
Node(); //1
Node(int item, Node *link = NULL); //2
[Code] .....
Implement: 1 2 3 4 5
and overload operator <<, >>, =
/*using GENERIC_COMMAND* A; as volatile generates error. but here i have to use union object as volatile i.e. volatile GENERIC_COMMAND* A; */
#include <iostream>
using namespace std;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
union GENERIC_COMMAND {
[Code] .....
Consider the class specification below. Write the prototype (i.e. header) of a member function to overload the insertion operator (i.e. <<). The << operator is to output the data members of an instance of class StudentTestScores into an output stream. Your definition should allow for chaining of output operations (e.g. cout << x << y; where x and y are of type StduentTestScires).
#include <string>
using namespace std;
class StudentTestScores{
private:
string studentName;
float *testScores; // used to point to an array of test scores
int numTestScores; // number of test scores
[code]....
I have a basic vector/point class where I've overloaded a bunch of arithmetical operators:
Code:
#pragma once
class point {
public:
point() {
}
point(float p_x, float p_y, float p_z) : x(p_x), y(p_y), z(p_z)
[Code] ...
I can use it fine like
Code:
point p(50,50,50);
point q(50,50,50);
point t = p * q + q;
However when I put this point type into a struct and try to access the members after passing it through by const reference:
Code:
struct sextic {
point a,b,c,d,e,f,g;
};
inline static sextic sexticDifference(const sextic &p_sextic1, c
[Code] ....
This gives me an "operator not defined" error for compilation.
I am a beginner, got confused about:
template<typename T> int compare(T &a,T &b);
int compare(const char *a,const char *b);
char ch_arr1[6]="world",ch_arr2[6]="hello";
compare(ch_arr1,ch_arr2);
After running the code above,we got to know the non-template function is called. What I know is that the array arguments ch_arr1,ch_arr2 will not be converted to char * because the parameters are references in the template functions.
ch_arr1,ch_arr2 need to be converted to const char * if compare(const char *a,const char *b) were called.
I just wanna know what exactly happened behind that? and why?
Is it possible to overload a variable in a derived class? Example:
struct Circle
{
int radius() const { return r; }
private:
int r;
}
struct Smiley : Circle
{
// inherits the function int radius() const, but doesn't return Smiley::r
private:
int r;
}
I'm still pretty new to classes so what am i doing in this code that is wrong.
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
using namespace std;
class BunnyInfo{
[Code]...
I want to be able to do
someFunction(MyObject)
rather than
someFunction(MyObject.getWhatIWant())
I know I can do &MyObject, MyObject() and MyObject[0] by overloading operators but is it possible with just plain old MyObject?
this is assuming that I have no access to someFunction(), i.e, it cannot be modified.
Firstly, is it legal to overload a template function in a class? This is what I did
class FILE_txt
{
public:
FILE_txt(const char* );
[Code]....
I want to overload pure virtual function from 3rd party SDK class to put my debug messages like that:
errorStatus aXsaction(){printf(_T("
abort transaction"));transactionManager->abortTransaction();}
#define transactionManager->abortTransaction() aXsaction()
But compiler complains on the minus sign:
error C2008: '-' : unexpected in macro definition
Is it possible to trick the compiler?
I'm trying to learn how to use variadic templates, and I decided a great example would be serializing a series of types into a stringstream:
Code:
// Send a fully constructed message.
virtual void send(ostringstream &msg) = 0;
// Construct a message from the arguments and send it.
// This is the usual entry point.
template <typename ...Args>
void send(Args ...args {
[Code] ....
This works fine, so far as I can tell. However, I decided to see if I could specialize the way certain types are serialized. I tried using a Google Protocol Buffer object as an example, and added this:
Code:
// Handle a protocol buffer type while constructing a message.
template <typename ...Args>
void send(ostringstream &msg,
const google::protobuf::MessageLite &protobuf, Args ...args) {
std::string msg_str = protobuf.SerializeAsString();
msg << msg_str;
send(msg,args...);
}
I would expect this overload to be preferred over the generic T overload when a protobuf object (which always inherits from MessageLite) is passed into send() anywhere in the list. However, this is not happening. I am getting an error message to the effect that << doesn't know how to deal with my concrete type, pointing at the T overload.
Is is possible to force derived classed to overload certain operators, like we do with pure virtual functions?
Is this possible to dynamically bind objects to their respective overloaded operators?
I am getting errors with undefined references to my base class vtable when I hackly try to overload: Code: operator+ I am not sure whether this is possible.
I'm working on a class that needs to read from cin, but also needs to read the input twice. I've decided that the mechanism I want to use is to write a simple wrapper class that will read from cin, then write to a tempporary file in the operator>> method, then it will, when the application calls seekg(0) to reset the file to the beginning of the file, my helper class will just switch the underlying stream from cin to the temporary file, then return reads from there.
I know there are some underlying issues to address if I need MORE functionality later, but for now, I know the basic functionality I need and from a logic level and how to make that happen. What I don't know how to do is handle the syntax of overloading the operator>> method.
I'm looking for a good syntax reference, or some sample code of how to properly overload this from a stream SOURCE perspective. I've written plenty of classes that overload operator>> from the DESTINATION perspective, but the exact same prototype doesn't work, at least not for primitives.
I defined a virtual class and three other classes based on it. I want to use them like this:
int main() {
Dirichlet_t D;
Neumann_t N;
Cauchy_t C;
PDEBoundary_t * B1=& D;
PDEBoundary_t * B2=& N;
PDEBoundary_t * B3=& C;
[Code] .....
but I got two major errors
1: "object f abstract type is not allowed" error.-----why not?
2: "the derived class must implement the inherited pure virtual method"-----Did't I?
I'm trying to understand the basics of oop ...
#include <iostream>
using namespace std;
template <typename T>
class max_vector {
private:
T* elemente;
int lungime;
[Code] ....
The purpose of this program is to overload two different operators one inside the class, and the other one outside using friend. The problem is that i get 1 error at the '*' one.
I'm having some issues with my code. For the produce function i am getting an error saying 'no instance of overload function produce() matches the argument list' and also for the lines buffer[head].data = message; buffer[head].time = current_time i get an error saying 'expression must have pointer to object type.
In the code i'm not sure if i passed the variables to the function correctly. I have attached the code .....
code produce.txt
I want to set an integer to zero when it easy equal to another integer, but it seems that the program for some reason won't set the integer to zero. Here is the example of that code:
#include <iostream>
using namespace std;
int main () {
int n = 2;
int r = 2;
if(n==r)
n++;
r*0;
cout << " n is " << n << endl;
cout << " r is " << r << endl;
}
What am I doing wrong, it should say that "n is 3" and "r is 0".
Code:
#include<stdio.h>
#include<conio.h>
void main()
[Code] .....
This program on running returns an error of "ILLEGAL USE OF POINTER".