using namespace std;
Namespaces eliminate the need to coordinate identifiers to assure that they are unique across different portions of a large project.
friend
function?
This access also removes any protection from incorrectly setting or manipulating the data in the class.
IE
const type & operator[](size_t d) const;Can be used to read the value and
type & operator[](size_t d);Can be used to write a new value.
PersonFactory
returns a reference to memory which is allocated on the stack. By the time this function returns, that memory has been deallocated and is no longer valid.
class PersonT { public: PersonT()=default; void SetName(string s); void SetAge(int i); string GetName(); int GetAge(); private: int age; string name; }; PersonT & PersonFactory() { PersonT data; data.SetName("Unknown"); data.SetAge(0); return data; } int main() { PersonT & person = PersonFactory(); cout << person.GetName() << " is " << person.GetAge() << endl; return 0; }
class Base { public: Base()=default; virtual ~Base()=default; void PrintClass() { cout << data;} void SetData(int d) {data = d;} private: int data; }; class Derived: public Base { public: void PrintClass(); void SetData(int d){Base::SetData(d);} void ChangeData(int d) {data = d;} }; int main() { Base * item = new Derived; item->ChangeData(x); item->PrintClass(); return 0; }
data
in the base class.
Line 21 is problematic as item
is a pointer to the base class and
ChangeData
is a member of the derived class.
SetData
function or make data
protected.
Line 21, make a virtual function ChangeData
in the base class,
class Derived1: virtual public Base { ... class Derived2: virtual public Base { ...
class Base { public: virtual ~Base() = default; ... private: int baseData[MAX_DATA_SIZE]; }; class Derived1: public Base { ... }; class Derived2: public Base { ... }; class Mixed: public Derived1, public Derived2 { ... };
Mode
that takes a vector of elements and returns the item occurring most frequently. If multiple items occur with equal maximum frequency, return the one with the minimum value.
template <typename T> T Mode(vector<T> data) { // assumes that there is data in the array. T frequent; T current; int frequentCount{1}; int currentCount; size_t i; sort(begin(data), end(data)); frequent = data[0]; // find the count of frequent; i = 1; while ( i < data.size() and data[i] == frequent) { frequentCount ++; i++; } if (i < data.size()) { current = data[i]; currentCount = 1; i++; } while (i < data.size()) { if (current == data[i]) { currentCount++; } else { if (currentCount > frequentCount) { frequent = current; frequentCount = currentCount; } current = data[i]; currentCount = 1; } i++; } if (currentCount > frequentCount) { frequent = current; frequentCount = currentCount; } return frequent; }