| re: A Few C++ Questions
Ill continue where Victor stopped ;-)
"tridion" <noemail@given.com> skrev i en meddelelse
news:NNCdncGU2qQNp5PfRVnyiQ@eclipse.net.uk...[color=blue]
> Could someone answer the following questions for me :
>[/color]
[snip][color=blue]
>
> 4. Discuss how you might improve this C++ code
>
> bool LessThan(Thing* pLeft, Thing* pRight)
> {
> // body of comparison function
> }
>
> typedef bool (*LessThanFnPtr)(Thing* pLeft, Thing* pRight);
>
> void Sort(Thing* pArray, int iSize, LessThanFnPtr pLessThan)
> {
> // bubble sort code using pLessThan to compare things
> }
>
> void DoSorting()
> {
> int iSize = 1000;
> Thing* pData = new Thing[iSize];
>
> // read in data
>
> Sort(pData, iSize, &LessThan);
>
> // use sorted data
> }[/color]
Use the standard library. Then this comes down to:
void DoSorting()
{
std::vector<Thing> data;
// read in data
std::sort(data.begin(),data.end()); // assuming Thing is comparable
and a "normal" sort is wanted.
}
[color=blue]
> 5. How would you improve the design of this C++ code? Point out any
> problems and the causes, and suggest or show a remedy.(Hint: errors)
>
> void SomeClass::SetValues()
> {
> Calculator* pCalculator = new Calculator();
> m_iVal1 = pCalculator->DoCalcSomething(1, 2);
> m_iVal2 = pCalculator->DoAnotherThing(m_iVal1);
> delete pCalculator;
> }[/color]
Do not use new here:
void SomeClass::SetValues()
{
Calculator pCalculator;
m_iVal1 = pCalculator.DoCalcSomething(1, 2);
m_iVal2 = pCalculator.DoAnotherThing(m_iVal1);
}
Note how the variable naming convention now gives the calculator object a
misleading name.
[color=blue]
>
> 6. The following C++ code is correct, but it's considered to be bad
> style. Discuss.
>
> // Somewhere we have
> bool bCondition(false);
>
> // Somewhere else, perhaps immediately after...
> int iValue;
> if (bCondition)
> iValue = 1;
> else
> iValue = 2;[/color]
You could use iValue = bCondition?1:2;
but considering the horrible style found in these samples I'm not sure this
is what is meant.
/Peter |