C++ :: Namespaces / Classes - Perform Operator Overload With Insertion Operator
Mar 22, 2013
I'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.
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
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;
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++
i 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
I have a class A, from which three classes Aa Ab and Ac are inherited. In class A I have defined some functions by virtual foo()=0, which I implemented in each subclass. Each class is written in a separated .h and .cpp file.
However, now I think it is possible to overload the operator+ INSIDE each class (including pure virtual in class A), such that something like
int main() { A *value = new Aa(); A value2 = *value + 1.0f; }
This should be realizable, because the operator+ is part of the Aa class. Now, I would like to do something like
int main() { A *value = new Aa(); A value2 = 1.0f + *value; }
This time, I expect I cannot overwrite the operator+, because it is not part of either class A or class Aa.
class Var { public: Var(); ~Var(); private: QMap<QString, QSharedPointer<Data>> _mapVars; }; QDataStream &operator<<(QDataStream &stream, const QSharedPointer<Data> p_data); QDataStream &operator>>(QDataStream &stream, Data &p_data)
I want to serialize _mapVars into a file. However, I have many other classes that are derived from Data, do i need to check for Data type inside the overloaded << functions like below in order to serialize ??? This doesn';t seem to be very correct ...
main3.cpp: In member function ‘FooB& FooB::operator=(const FooC&)’: main3.cpp:46:44: error: expected ‘(’ before ‘other’ main3.cpp:46:49: error: no matching function for call to ‘Foo<C>::Foo(const FooC&)’ main3.cpp:46:49: note: candidates are: main3.cpp:19:2: note: Foo<T>::Foo() [with T = C] main3.cpp:19:2: note: candidate expects 0 arguments, 1 provided main3.cpp:16:25: note: Foo<C>::Foo(const Foo<C>&) main3.cpp:16:25: note: no known conversion for argument 1 from ‘const FooC’ to ‘const Foo<C>&’
so i was trying to find out how to do unbuffered input in linux and came across this class: [URL] . i didnt like how i had to create a new instance of it each time i wanted to use it, so i made the functions static and renamed the class to Buffer. i could then call it like this: Buffer::On(); Buffer::Off();. My question is, when doing something like that where the class consists of two functions that can exist indepently of another, which is better: a class like what i did or wrapping it in a namespace?
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; }
but how do you use an array as the condition, how will the code look?For example i want to write
Code:
string numbers[5] = {"one","two","three","four","five"}; numbers == "one" ? thumb : again; thumb and again will replace something else. Don't worry about them.
how do i say that if the numbers array is representing "one" then it replaces as "thumb", otherwise "again".
Is it usual to rely completly on the new operator in constructors/copy constructors. What if new trows an exception? The application ends and that's it? The new operator can be placed where it can't be catch like in constructor initialization list. What kind of practice I should adopt when using "new" in those cases?
The sample code below is taken from here... [URL] ....
class MemoryBlock { public:
// Simple constructor that initializes the resource. explicit MemoryBlock(size_t length) : _length(length) , _data(new int[length])
In that situation, << does not call the overloaded function, but rather calls the << method defined in the i/o library, which prints a message to the controlling terminal. So once it prints the message to the terminal, it then returns the out instance. Why return the out instance rather than a boolean like true? As you can see from the example, once the message is printed to terminal, out is not used anymore.
In stl map, if I insert two keys, say a and b. It looks like compare operator is called twice. First time a<b is called and second time b<a is called. Why are both a<b and b<a called?
Code: #include <iostream>#include <iomanip> using namespace std; class Score { private: // Value at which we'll shift digits from million_counter to billion_counter static const int THRESHOLD = 1000000000;
[Code] ....
It gives the errors: line 105 error: million_counter was not declared in this scope line 106 error: normalizeScore was not declared in this scope line 110 error: million_counter was not declared in this scope and more of that until line 170 error: no match for 'operator<<' in 'std:perator<< <std::char_traits<char> >((* & std::cout), ((const char*)"a+b is ")) <<operator+((*c(const Score*) (& a)), (*(const Score*)(& b)))'
I thought that because i declared friend functions, they would be able to access the private variables of the class.
I have done alot of googling for the scope resolution operator and Ive gained a bit of an understanding as to what it does i know it can distinguish between global and local variables, but I see it used to access methods/members of classes such as this example, why not just use a dot instead to access it?:
sql:: Driver *driver;
Why is the scope resolution operator being used here?