I have a class strings:
class strings
{
protected:
string *ptr;
int size;
public:
strings() {
ptr = NULL;
size = -1;
}
strings(int size) {
this->size = size;
ptr = new string[size];
}
string* retPtr() {
return ptr;
}
void setPtr(int size)
{
ptr = new string[size];
this->size = size;
}
strings(const strings& obj) {
this->size = obj.size;
for (int i = 0;i < size;++i)
this->ptr[i] = obj.ptr[i];
}
friend istream& operator>>(istream& input, strings& obj) {
cin.ignore();
cout << "Enter " << obj.size << " string one by one:\n";
for (int i = 0;i < obj.size;++i)
{
getline(input, obj.ptr[i]);
}
return input;
}
friend ostream& operator<<(ostream& output, const strings& obj) {
cout << "Strings are:\n";
for (int i = 0;i < obj.size;++i)
output << obj.ptr[i] << "\n";
return output;
}
void operator =(const strings& obj)
{
this->size = obj.size;
for (int i = 0;i < size;++i)
ptr[i] = obj.ptr[i];
}
~strings()
{
delete[]ptr;
}
};
Another class stringsFromNumbers:
class stringsFromNumbers:public strings
{
int numbers;
public:
stringsFromNumbers(){
numbers = -1;
}
stringsFromNumbers(int size, int numbers):strings(size){
this->numbers = numbers;
}
stringsFromNumbers(const stringsFromNumbers& obj)
{
this->numbers = obj.numbers;
this->size = obj.size;
for (int i = 0;i < size;++i)
this->ptr[i] = obj.ptr[i];
}
friend istream& operator>>(istream& input, stringsFromNumbers& obj) {
cin.ignore();
cout << "Enter " << obj.size << " string one by one:\n";
for (int i = 0;i < obj.size;++i)
{
getline(cin, obj.ptr[i]);
}
return input;
}
friend ostream& operator<<(ostream& output, const stringsFromNumbers& obj) {
cout << "Numbers are: " << obj.numbers;
cout << "\nStrings are:\n";
for (int i = 0;i < obj.size;++i)
output << obj.ptr[i] << "\n";
return output;
}
void operator =(const stringsFromNumbers& obj)
{
this->numbers = obj.numbers;
this->size = obj.size;
for (int i = 0;i < size;++i)
this->ptr[i] = obj.ptr[i];
}
~stringsFromNumbers()
{
delete[] ptr;
}
};
Whenever i try execute this line of code:
stringsFromNumbers obj2(N, P);
where N and P are valid integers, I get an "Access Reading Violation", do you see something wrong in the code?
I have been stuck on this for almost 2 hours. I have tried debugging and fixing it, i have also tried multiple other methods. The exception takes me to this function:
inline void _Container_base12::_Orphan_all() noexcept {
#if _ITERATOR_DEBUG_LEVEL == 2
if (_Myproxy) { // proxy allocated, drain it
_Lockit _Lock(_LOCK_DEBUG);
for (auto _Pnext = &_Myproxy->_Myfirstiter; *_Pnext; *_Pnext = (*_Pnext)->_Mynextiter) {
(*_Pnext)->_Myproxy = nullptr;
}
_Myproxy->_Myfirstiter = nullptr;
}
#endif // _ITERATOR_DEBUG_LEVEL == 2
}
The problem is with this function most probably but how can it be fixed?
stringsFromNumbers(int size, int numbers):strings(size){
this->numbers = numbers;
}
Both stringsFromNumbers::~stringsFromNumbers and strings::strings call delete[] on ptr, so the array is attempted to be freed twice; the second time causes an issue.
Only one of these classes should be responsible for managing the lifecycle of ptr. Remove the delete[] from stringsFromNumbers::~stringsFromNumbers.
If in some other case you've got a valid reason to free the array in the destructor of a subclass, make sure the parent class destructor is able to deal with the new state (e.g. by setting ptr to nullptr after deleting it), but in general you should avoid the complexity of making both classes sharing responsibility for freeing the memory.
Related
I finished some code that prints out how many times a word shows up. However, when I finished and tried to run the code on a different compiler it did not work. Firstly, here is a picture of my code working on my initial file:
But when I used a different compiler (onlinegdb) I get this error:
The thing that confused me the most is; when I try and replicate the file into a new VS Code .cpp file, it does not work. It runs the code but then prints out nothing. When I went into gdb I find this error:
If anyone knows where the segmentation fault/std::length_error are happening at please let me know, and if you have any recommendations that would be great! Also, knowing why I get different results on the same compiler (VS Code) would also be helpful. Here is my code:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
class WordOccurrence
{
public:
WordOccurrence(const string& word="", int num=1)
{
word_ = word;
num_ = num;
}
bool matchWord(const string & compare)
{
if(word_ == compare)
return true;
else
return false;
}
void increment()
{
num_++;
}
string getWord() const
{
return word_;
}
int getNum() const
{
return num_;
}
private:
string word_;
int num_;
};
class WordList
{
public:
friend bool equal(const WordList&, const WordList&);
WordList();
WordList(const WordList &);
~WordList();
WordList operator= (const WordList &);
void addWordFile(WordList w);
void addWord(const string &);
void print();
private:
WordOccurrence *wordArray_;
int size_;
};
WordList::WordList()
{
size_ = 0;
wordArray_ = new WordOccurrence [size_];
}
WordList::WordList (const WordList &neww)
{
size_ = neww.size_;
wordArray_ = new WordOccurrence[size_];
for (int i = 0; i <= (size_ - 1); i++)
wordArray_[i] = neww.wordArray_[i];
}
WordList::~WordList ()
{
delete [] wordArray_;
}
WordList WordList::operator= (WordList const &overload)
{
WordList temp(overload);
swap(wordArray_, temp.wordArray_);
swap(size_, temp.size_);
return *this;
}
void WordList::addWord(const string& word)
{
if(size_ == 0)
{
WordOccurrence *first_array = new WordOccurrence[1];
first_array[0] = word;
delete[] wordArray_;
wordArray_ = first_array;
delete[] first_array;
size_++;
return;
}
//if the word is already in the array, we increase the count of it by 1
for (int i = 0; i < size_; i++)
{
if (wordArray_[i].matchWord(word))
{
wordArray_[i].increment();
return;
}
}
//if it is not in the array already, we need to increase its size and then add the new word to the wordarray.
WordOccurrence *new_array = new WordOccurrence[size_+1];
for (int i = 0; i < size_; i++)
{
new_array[i] = wordArray_[i];
}
new_array[size_] = WordOccurrence(word);
delete[] wordArray_;
size_++;
wordArray_ = new_array;
delete[] new_array;
}
void WordList::print()
{
//to output to a file because when we get a lot of words it's kinda hard to see on just the terminal
ofstream myfile ("output.txt");
WordList sortedList(*this);
//Sorting from smallest to largest
int smallest = wordArray_[0].getNum();
for (int i = 1; i < size_; i++)
{
//stores the smallest value into smallest
if(wordArray_[i].getNum() < smallest)
smallest = wordArray_[i].getNum();
}
int location = 0;
//stores values from start to finish in the new list starting at location sortedList[0]
while(location < size_)
{
for(int i = 0; i < size_; i++)
{
//runs through the new list until it finds a value that is apart of the smallest/rarest words
if(wordArray_[i].getNum() == smallest)
{
sortedList.wordArray_[location] = wordArray_[i];
location++;
}
}
//increases the value of smallest allowing for numbers with greater found values to be sorted
smallest++;
}
//prints out the sorted version of wordarray
for(int i = 0; i < size_; i++)
{
string word = sortedList.wordArray_[i].getWord();
int count = sortedList.wordArray_[i].getNum();
cout << "Word: " << word << " Amount: " << count << endl;
//for longer amounts of text, it was hard to see on a editor so I also have it out to a file.
myfile << "Word: " << word << " Amount: " << count << endl;
}
}
int main()
{
WordList w;
w.addWord("one");
w.addWord("one");
w.addWord("two");
w.addWord("three");
w.addWord("four");
w.addWord("four");
w.addWord("four");
w.addWord("four");
w.addWord("five");
w.addWord("five");
w.addWord("five");
cout << "Sorted list" << endl;
w.print();
}
This is bugged
WordOccurrence *first_array = new WordOccurrence[1];
first_array[0] = word;
delete[] wordArray_;
wordArray_ = first_array;
delete[] first_array;
size_++;
return;
You assign first_array to wordArray_ and then you delete it. This leaves wordArray_ as an invalid pointer. Just remove delete[] first_array;. Two deletes and only one new should have been a clue that something was wrong.
Same bug later on in the same function
WordOccurrence *new_array = new WordOccurrence[size_+1];
for (int i = 0; i < size_; i++)
{
new_array[i] = wordArray_[i];
}
new_array[size_] = WordOccurrence(word);
delete[] wordArray_;
size_++;
wordArray_ = new_array;
delete[] new_array;
delete[] new_array; should not be there.
I'm trying to concatenate two arrays and at the end concatenate int, for example: result = arg + arg + 2;
I'm getting "read access violation" at + operator overloading.
I wrote the error and warning in comments below.
My code:
Main:
#include <iostream>
#include <string>
#include "CTable.h"
int main() {
CTable c_tab1, c_tab0;
c_tab0.SetNewSize(3);
c_tab1.SetNewSize(2);
c_tab0.SetValueAt(0, 22);
c_tab0.SetValueAt(1, 23);
c_tab0.SetValueAt(2, 24);
c_tab0.Print();
c_tab1.SetValueAt(0, 31);
c_tab1.SetValueAt(1, 32);
c_tab1.Print();
CTable c_tab3 = (c_tab0 + c_tab1 + 111);
c_tab3.Print();
return 0;
}
Class CTable:
#include <iostream>
#include <string>
using namespace std;
class CTable {
public:
CTable();
CTable(string sName, int iTableLen);
CTable(const CTable& pcOther);
CTable* pcClone();
~CTable();
void ShowName();
void ShowSize();
void SetName(string sName);
bool SetNewSize(int iTableLen);
void SetValueAt(int iOffset, int iNewVal);
void Print();
CTable& operator+(const CTable& pcNewTable);
CTable operator+(int iNewVal) const;
CTable& operator=(const CTable& pcNewVal) {
if (this != &pcNewVal) {
for (int i = 0; i < i_size; i++) {
this->piTable[i] = pcNewVal.piTable[i];
}
}
return *this;
}
private:
string s_name;
int i_size;
int* piTable;
const int SIZE = 10;
const string NAME = "Name";
};
#include <iostream>
#include <string>
#include "CTable.h"
#include <algorithm>
using namespace std;
CTable::CTable() {
s_name = NAME;
cout << "bezp: " << s_name << endl;
piTable = new int[SIZE];
i_size = SIZE;
}
CTable::CTable(string sName, int iTableLen) {
s_name = sName;
cout << "parametr: " << sName << endl;
piTable = new int[iTableLen];
i_size = iTableLen;
}
CTable::CTable(const CTable& pcOther) {
s_name = pcOther.s_name + "copied";
piTable = new int[pcOther.i_size];
i_size = pcOther.i_size;
for (int i = 0; i < pcOther.i_size; i++) {
piTable[i] = pcOther.piTable[i];
}
}
CTable::~CTable() {
delete[] piTable;
}
void CTable::SetName(string sName) {
s_name = sName;
}
bool CTable::SetNewSize(int iTableLen) {
if (iTableLen <= 0) {
cout << "Length has to be greater than 0" << endl;
return false;
}
int* pi_newTable = new int[iTableLen];
for (int i = 0; i < iTableLen; i++) {
pi_newTable[i] = piTable[i];
}
delete this->piTable;
this->i_size = iTableLen;
this->piTable = pi_newTable;
return true;
}
CTable* CTable::pcClone() {
CTable* ct = new CTable(s_name, i_size);
return ct;
}
void CTable::ShowName() {
cout << "Name: " << s_name << endl;
}
void CTable::ShowSize() {
cout << "Size: " << i_size << endl;
}
void CTable::SetValueAt(int iOffset, int iNewVal) {
if (iOffset >= this->i_size) {
return;
}
piTable[iOffset] = iNewVal;
}
void CTable::Print() {
for (int i = 0; i < i_size; i++) {
cout << piTable[i] << " ";
}
cout << endl;
}
CTable& CTable::operator+(const CTable& pcNewTable) {
CTable result("new_int", this->i_size);
result.i_size = (i_size + pcNewTable.i_size);
result.piTable = new int[i_size + pcNewTable.i_size];
for (int i = 0; i < i_size; i++) {
result.piTable[i] = piTable[i];
}
for (int i = 0; i < (pcNewTable.i_size); i++) {
result.piTable[i+i_size] = pcNewTable.piTable[i];
}
return result; //Warning C4172 returning address of local variable or temporary: result
}
CTable CTable::operator+(int iNewVal) const {
CTable result("new_int", this->i_size);
result.i_size = (i_size + 1);
result.piTable = new int[i_size + 1];
for (int i = 0; i < i_size; i++) {
result.piTable[i] = piTable[i]; //Exception thrown: read access violation. **this->piTable** was 0x1110122.
}
result.piTable[i_size + 1] = iNewVal;
return result;
}
What should I correct? I'm not sure about assigment operator overload, is it okay?
The member function SetNewSize has undefined behavior. In this loop
int* pi_newTable = new int[iTableLen];
for (int i = 0; i < iTableLen; i++) {
pi_newTable[i] = piTable[i];
}
it 1) uses uninitialized values because the array was not initialized and 2) iTableLen can be gretaer than the current value of i_size. You should at least zero initialize the array in constructors.
The copy assignment operator aslo has undefined behabior because the number of elements of the array of the object pcNewVal can be less than the number of elements of the array in the assigned object.
The first overloaded operator + also have undefined behavior. For starters as the warning says the operator returns reference to the local object result that will not be alive after exiting the operator. Secondly, there is a memory leak necause the array of the object is allocated anew and the previuous allocated memory in the constructor is not freed.
CTable result("new_int", this->i_size);
result.i_size = (i_size + pcNewTable.i_size);
result.piTable = new int[i_size + pcNewTable.i_size];
//...
The second overloaded operator + also has undefined behavior. As in the previous operator there is a memory leak.
In this statement
result.piTable[i_size + 1] = iNewVal;
there is an access memory outside the allocated array. There should be
result.piTable[i_size] = iNewVal;
I made a dynamic array with template. The problem is that when I don't keep there pointers (for example: Tab<string> da;) my destructor doesn't have to clear it and throws error caused by delete arr[i];. My question is if I can put some if condition(in which I would put clear() method) which would tell me if my array keeps pointers. In the simplest way I can use clear() in main when I keeps there pointers, but my teacher wants me to make it like I wrote above.
I tried using is_pointer, but it doesn't work or I use it wrong.
Any suggestions?
#ifndef TABLICA_H
#define TABLICA_H
#include <iostream>
#include <type_traits>
using namespace std;
template<class T>
class Tab
{
public:
int size = 0;
int max_size = 1;
T* arr;
bool isDynamic = false;
Tab()
{
arr = new T[max_size];
}
~Tab()
{
clear();
delete[] arr;
}
void check_size()
{
if (size == max_size)
{
max_size = max_size * 2;
T* arr2 = new T[max_size];
for (int i = 0; i < size; i++)
{
arr2[i] = arr[i];
}
delete[] arr;
arr = arr2;
}
}
void push_back(const T& value)
{
check_size();
arr[size] = value;
size++;
}
T return_by_index(int index)
{
if (index<0 || index > size)
{
return NULL;
}
return arr[index];
}
bool replace(int index, const T& value)
{
if (index<0 || index > size)
{
return false;
}
arr[index] = value;
return true;
}
void print(int number)
{
cout << "Rozmiar obecny: " << size << endl;
cout << "Rozmiar maksymalny: " << max_size << endl;
cout << "Adres tablicy: " << arr << endl;
cout << "Kilka poczatkowych elementow tablicy " << "(" << number << ")" << endl;
for (int i = 0; i < number; i++)
{
cout << *arr[i] << endl;
}
}
void clear()
{
for (int i = 0; i < size; i++)
{
delete arr[i];
}
}
};
#endif
//Source:
#include <iostream>
struct object
{
int field1;
char field2;
object()
{
field1 = rand() % 10001;
field2 = rand() % 26 + 'A';
}
};
ostream& operator<<(ostream& out, const object& o)
{
return out << o.field1 << " " << o.field2;
}
int main()
{
Tab < object* >* da = new Tab < object* >();
delete da;
system("PAUSE");
return 0;
Trying to familiarize myself with the "Rule of 3" and Im having trouble getting a Copy Constructor to work. One of the class private members is returning 0 when it should have a value of 3.
Im not sure as to why when the Copy Constructor function is performed, a value of 0 is supplied to that classes private member. The member in question is theSize which is returned via the size() function in class.cpp.
class.h
class Catalog {
public:
Catalog (int maxCapacity = 100)
int size() const;
int capacity() const;
void add (Book b);
Catalog(const Catalog& c);
~Catalog();
Catalog& operator= (constCatalog& c) {
if (this != &c) {
delete[] books;
books = new Book[theCapacity];
*books = *(c.books);
}
return *this;
}
private:
Book* books;
int theCapacity;
int theSize;
};
class.cpp
Catalog::Catalog(int maxCapacity) {
theCapacity = maxCapacity;
theSize = 0;
books = new Book[theCapacity];
}
int Catalog::size() const {
return theSize();
}
int Catalog::capacity() const {
return theCapacity;
}
void Catalog::add (Book b)
{
if (theSize < theCapacity || contains(b.getID())) {
if (theSize == 0) {
books[0] = b;
theSize++;
}
else {
if (!contains(b.getID())) {
int i = theSize;
for (; i && b < books[i-1]; --i) {
books[i] = books[i - 1];
}
books[i] = b;
for (; i; --i) {
books[i - 1] = books[i - 1];
}
theSize++;
}
else {
for (int i = 0; i < theSize; ++i) {
if (b == books[i]) {
books[i] = b;
}
}
}
}
// Debugging only
/*for (int i = 0; i < theSize; i++) {
//cout << books[i] << endl;
}*/
}
}
bool Catalog::contains(std::string bookID) const
{
for (int i = 0; i < theSize; ++i)
{
if (books[i].getID() == bookID)
return true;
}
return false;
}
Catalog::Catalog(const Catalog& c) {
books = new Book[c.theSize];
for (int i = 0; i < c.theSize; i++) {
books[i] = c.books[i];
}
Catalog::~Catalog() {
delete[] books;
}
Later in main.cpp when I call c1.size() where c1 is the result of return c in another function that through use of the debugger comes from the Copy Constructor and then goes to the Destructor. However, c1.size() is returning as 0 though the Copy Constructor theSize = c.size() has a value of 3 when stepped through.
book.cpp
using namespace std;
/**
* Create a book.
*
* #param id the Gutenberg ID for this book
* #param authorInfo the author of the book
* #param title the title of the book
*/
Book::Book (std::string theId, std::string authorInfo, std::string theTitle)
: id(theId), authorName(authorInfo), title(theTitle)
{
}
bool Book::operator< (const Book& b) const
{
return id < b.id;
}
bool Book::operator== (const Book& b) const
{
return (id == b.id);
}
std::ostream& operator<< (std::ostream& out, const Book& b)
{
cout << b.getID() << "\t"
<< b.getAuthor() << "\t"
<< b.getTitle();
return out;
}
std::istream& operator>> (std::istream& in, Book& b)
{
string line;
getline (in, line);
if (!in.good())
return in;
int tab1 = line.find ("\t");
int tab2 = line.find ("\t", tab1+1);
string id = line.substr(0, tab1);
string author = line.substr (tab1+1, tab2-tab1-1);
string title = line.substr(tab2+1);
b.setID (id);
b.setAuthor (author);
b.setTitle (title);
return in;
}
main.cpp
using namespace std;
Catalog readCatalog(const string& fileName)
{
Catalog c;
ifstream in (fileName);
in >> c;
in.close();
return c;
}
Catalog mergeCatalogs (const Catalog& cat1, const Catalog& cat2)
{
Catalog result (cat1.size() + cat2.size());
int i = 0;
int j = 0;
while (i < cat1.size() && j < cat2.size())
{
Book b1 = cat1.get(i);
Book b2 = cat2.get(j);
if (b1.getID() < b2.getID())
{
result.add(b1);
++i;
}
else
{
result.add(b2);
++j;
}
}
while (i < cat1.size())
{
result.add(cat1.get(i));
++i;
}
while (j < cat2.size())
{
result.add(cat2.get(j));
++j;
}
return result;
}
void mergeCatalogFiles (const string& catalogFile1, const string& catalogFile2)
{
Catalog c1, c2;
c1 = readCatalog(catalogFile1);
cout << catalogFile1 << " contained " << c1.size() << " books." << endl;
c2 = readCatalog(catalogFile2);
cout << catalogFile2 << " contained " << c2.size() << " books." << endl;
Catalog c3 = mergeCatalogs (c1, c2);
cout << "Their merge contains " << c3.size() << " books." << endl;
cout << c3 << flush;
}
int main (int argc, char** argv)
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] <<
"catalogFile1 catalogFile2" << endl;
return -1;
}
string file1 = argv[1];
string file2 = argv[2];
mergeCatalogFiles (file1, file2);
if (Counted::getCurrentCount() == 0)
{
cout << "No memory leak detected." << endl;
return 0;
}
else
{
cout << "Memory leak detected: " << Counted::getCurrentCount() << endl;
return -2;
}
}
Follow rule of zero: use std::vector<Book> to replace the array pointer and the size.
Your capacity is a limit on the size.
When at capacity. use equal range to find where to insert, replace last element then std rotate.
Managing both resources and business logic in the same class is bug prone. Do one thing at a time.
Try something more like this instead:
class Catalog
{
public:
Catalog (int maxCapacity = 100);
Catalog(const Catalog& c);
~Catalog();
int size() const;
int capacity() const;
void add (const Book &b);
Book* find(const std::string &bookID) const;
Catalog& operator= (Catalog c);
private:
Book* books;
int theCapacity;
int theSize;
void swap(Catalog &c);
};
#include "class.h"
#include <algorithm>
Catalog::Catalog(int maxCapacity)
{
theCapacity = maxCapacity;
theSize = 0;
books = new Book[theCapacity];
}
Catalog::Catalog(const Catalog& c)
{
theCapacity = c.theCapacity;
books = new Book[theCapacity];
for(int i = 0; i < c.theSize;; ++i)
books[i] = c.books[i];
theSize = c.theSize;
}
Catalog::~Catalog()
{
delete[] books;
}
Catalog& Catalog::operator= (const Catalog &c)
{
if (this != &c)
Catalog(c).swap(*this);
return *this;
}
void Catalog::swap(Catalog &c)
{
std::swap(books, c.books);
std::swap(theSize, c.theSize);
std::swap(theCapacity, c.theCapacity);
}
int Catalog::size() const
{
return theSize;
}
int Catalog::capacity() const
{
return theCapacity;
}
void Catalog::add (const Book &b)
{
Book *book = find(b.getID());
if (book) {
*book = b;
}
else if (theSize < theCapacity)
{
int i;
for (i = theSize; i && b < books[i-1]; --i) {
books[i] = books[i - 1];
}
books[i] = b;
++theSize;
}
// Debugging only
/*
for (int i = 0; i < theSize; ++i) {
cout << books[i] << endl;
}
*/
}
Book* Catalog::find(const std::string &bookID) const
{
for (int i = 0; i < theSize; ++i)
{
if (books[i].getID() == bookID)
return &books[i];
}
return 0;
}
That being said, this would be much simpler and easier to manage if you use std::vector and STL algorithms. Let the STL do the hard work for you:
#include <vector>
class Catalog
{
public:
Catalog (int initialCapacity = 100);
int size() const;
int capacity() const;
void add (const Book &b);
Book* find(const std::string &bookID) const;
private:
std::vector<Book> books;
};
#include "class.h"
#include <algorithm>
Catalog::Catalog(int initialCapacity)
{
books.reserve(initialCapacity);
}
int Catalog::size() const
{
return books.size();
}
int Catalog::capacity() const
{
return books.capacity();
}
void Catalog::add (const Book &b)
{
Book *book = find(b.getID());
if (book) {
*book = b;
}
else {
books.insert(std::upper_bound(books.begin(), books.end(), b), b);
}
// Debugging only
/*
for (Book &book: books) {
cout << book << endl;
}
*/
}
Book* Catalog::find(const std::string &bookID) const
{
auto iter = std::find_if(books.begin(), books.end(), [&bookID](const Book &b){ return (b.getID() == bookID); });
if (iter != books.end())
return &*iter;
return 0;
}
I am not sure what I am doing wrong here but I used Google and found almost the identical code to mine but they did not claim an error. Our assignment is to overload the insertion operator. The problem is that I get an error in the driver for every time I pass SAM or JOE. The error states: Error 2 error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'MyVector' (or there is no acceptable conversion).
Any help is appreciated. Please note that I have not completed this assignment and if another function doesn't seem right, it may be because I haven't work on it.
Thanks in advance.
Driver.cpp
#include <iostream>
#include "MyVector.h"
using namespace std;
// the printV function
// used to test the copy constructor
// parameter: a MyVector object
void printV(MyVector);
int main()
{
cout << "\nCreating a vector Sam of size 4.";
MyVector sam(4);
cout << "\nPush 12 values into the vector.";
for (int i = 0; i < 12; i++)
sam.push_back(i);
cout << "\nHere is sam: ";
cout << sam;
cout << "\n---------------\n";
cout << "\nCreating a vector Joe of size 4.";
MyVector joe(4);
cout << "\nPush 6 values into the vector.";
for (int i = 0; i < 6; i++)
joe.push_back(i * 3);
cout << "\nHere is joe: ";
cout << joe;
cout << "\n---------------\n";
cout << "\nTest the overloaded assignment operator \"joe = sam\": ";
joe = sam;
cout << "\nHere is sam: ";
cout << sam;
cout << "\n---------------\n";
cout << "\nHere is joe: ";
cout << joe;
cout << "\n---------------\n";
// pass a copy of sam by value
printV(sam);
cout << endl;
system("PAUSE");
return 0;
}
void printV(MyVector v)
{
cout << "\n--------------------\n";
cout << "Printing a copy of a vector\n";
cout << v;
}
My Vector.h
#pragma once
class MyVector
{
private:
int vSize;
int vCapacity;
int* vArray;
void grow();
public:
MyVector();
MyVector(int n);
MyVector(const MyVector& b);
int size() const;
int capacity() const;
void clear();
void push_back(int n);
int& at(int n) const;
MyVector& operator=(const MyVector& rho);
~MyVector();
};
MyVector.cpp
#include "MyVector.h"
#include <iostream>
using namespace std;
MyVector::MyVector()
{
vArray = nullptr;
vSize = 0;
vCapacity = 0;
}
MyVector::MyVector(int n)
{
vArray = new int[vCapacity];
vSize = 0;
vCapacity = n;
}
MyVector::MyVector(const MyVector& b)
{
vSize = b.size();
vArray = new int[vSize];
for (int i = 0; i < b.size(); i++)
{
this->vArray[i] = b.vArray[i];
}
}
int MyVector::size() const
{
return vSize;
}
int MyVector::capacity() const
{
return vCapacity;
}
void MyVector::clear(void)
{
if (vArray != nullptr)
{
delete[] vArray;
vArray = nullptr;
vSize = 0;
vCapacity = 0;
}
}
void MyVector::push_back(int n)
{
if (vCapacity == 0)
{
vCapacity++;
int* tmp = new int[vCapacity];
delete[] vArray;
vArray = tmp;
}
if (vSize >= vCapacity)
{
grow();
}
vArray[vSize] = n;
vSize++;
}
void MyVector::grow()
{
vCapacity = vCapacity + vCapacity;
int* tmp = new int[vCapacity];
for (int i = 0; i < vSize; i++)
{
tmp[i] = vArray[i];
}
delete[] vArray;
vArray = tmp;
}
int& MyVector::at(int index) const
{
if (index >= 0 && index<vSize)
{
return vArray[index];
}
else
{
throw index;
}
}
MyVector& MyVector::operator=(const MyVector& rho)
{
// test for self assignment
if (this == &rho)
return *this;
// clean up array in left hand object (this)
delete[] this->vArray;
// create a new array big enough to hold right hand object's data
vSize = rho.size();
this->vArray = new int[vSize];
// copy the data
for (int i = 0; i < rho.size(); i++)
{
this->vArray[i] = rho.vArray[i];
}
// return this object
return *this;
}
MyVector::~MyVector()
{
if (vArray != nullptr)
{
clear();
}
}
ostream& operator<<(ostream& out, const MyVector& rho)
{
for (int i = 0; i < rho.size(); i++)
{
out << rho.at(i);
}
return out;
}
Declare std::ostream& operator<<(std::ostream& out, const MyVector& rho) in My Vector.h. That function is used in Driver.cpp, therefore Driver.cpp must know about it.
If you do this, you should also #include <ostream> in My Vector.h.
To be able to use your offending operator<<() in main(), there needs to be a declaration of it visible to the compiler when compiling Driver.cpp.
That means you need to declare your operator<<() in MyVector.h.
Having the definition of operator<<() in MyVector.cpp is fine, but that is not visible to the compiler when compiling Driver.cpp