Start New Discussion within our Software Development Community

I was absent for the discussion and lab due to illness and I am at a total loss as to how to do this assignment.

Implement the my_string class in header file my_string.h, so that the test code given below reports SUCCESS.

// test_my_string.cpp

#include <iostream>
#include <string>
#include <cassert>
#include "my_string.h"

using namespace std;

//#define STRING string
#define STRING my_string

int main()
{
   STRING s1; // s1 == ""
   assert(s1.length() == 0);

   STRING s2("hi");  // s2 == "hi"
   assert(s2.length() == 2);

   STRING s3(s2);  // s3 == "hi"
   assert(s3.length() == 2);
   assert(s3[0] == 'h');
   assert(s3[1] == 'i');

   s1 = s2;  // s1 == "hi"

   s3 = "bye";  // s3 == "bye"
   assert(s3.length() == 3);
   assert(s3[0] == 'b');
   assert(s3[1] == 'y');
   assert(s3[2] == 'e');
   
   s1 += "re";  // s1 == "hire"
   assert(s1.length() == 4);
   assert(s1[0] == 'h');
   assert(s1[1] == 'i');
   assert(s1[2] == 'r');
   assert(s1[3] == 'e');

   cout << "SUCCESS" << endl;

I cannot get the program to get past assert(s3[0] == 'h'); nor can I get cout << s3[0]; to work.

What am I missing here?

Nevermind...

I got it to work using

char &operator[](unsigned int index) {
   return str[index];
}
This article has been dead for over six months. Start a new discussion instead.