Passing references in c++ - c++

I am writing a program for overloading "[ ] " operator on arrays .Here is my code
/ / A safe array example.
#include <iostream>
#include <cstdlib>
using namespace std;
class atype {
int a[3];
public:
atype(int i, int j, int k) {
a[0] = i;
a[1] = j;
a[2] = k;
}
int &operator[](int i);
};
// Provide range checking for atype.
int &atype::operator[](int i)
{
if(i<0 || i> 2) {
cout << "Boundary Error\n";
exit(1);
}
return a[i];
}
int main()
{
atype ob(1, 2, 3);
cout << ob[1]; // displays 2
cout << " ";
ob[1] = 25; // [] appears on left
cout << ob[1]; // displays 25
ob[3] = 44; // generates runtime error, 3 out-of-range
return 0;
}
In the class we are declaring as
int &operator[](int i);
and outside the class it is defined as
int &atype::operator[](int i)
It should be int atype::&operator[](int i)
but it is giving me error.
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2589: '&' : illegal token on right side of '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): warning C4091: '' : ignored on left of 'int' when no variable is declared
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2143: syntax error : missing ';' before '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(17): error C2059: syntax error : '::'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2143: syntax error : missing ';' before '{'
1>c:\users\abc\documents\visual studio 2010\projects\[]overl\[]overl\[]overl.cpp(18): error C2447: '{' : missing function header (old-style formal list?)
But when I tried int &atype::operator[](int i)
it worked.Could anybody explain that are we passing reference to class or operator[](int i)

The general syntax is
<return type> class-name :: function-name (argument-list)
In your case the return type is a reference to an integer i.e. int &
int &atype::operator[](int i) is only the correct syntax

Your operator[] returns a reference to the element requested by index. In this case your array is of int type so it will be a reference-to-an-int, ie: int& as a return value.

Related

C++ error C2143 syntax error : missing ';' before function name

I have header file :
#ifndef VIP_TICKET_H
#define VIP_TICKET_H
#include "ticket.h"
class VIPTicket : public Ticket
{
public:
enum VIPType { FIRST_CLASS, FAST_LINE };
VIPType getTicketType() const;
private:
VIPType type;
};
#endif
and it's cpp file
#include "vipTicket.h"
VIPType VIPTicket::getTicketType() const
{
return type;
}
the error says " error C2143: syntax error : missing ';' before 'VIPTicket::getTicketType' "
this error is very confusing.. i guess it's not a ';' that is missing but probably something else wrong with the code that I can't put my finger on..
The problem is this definition
VIPType VIPTicket::getTicketType() const
{
...
}
When you define this function you have to remember that VIPType is not in the global scope, but in the scope of the VIPTicket class, so you have to explicitly mention the scope:
VIPTicket::VIPType VIPTicket::getTicketType() const
{
...
}

error C2065: undeclared identifier in template function

I'm a newbie in C++ and i'm trying to put a little project on wheels, but i'm having a hard time with those errors and i don't know what i'm doing wrong. I think, i've included all neccesary header files.
What i'm doing wrong?
Thank you in advance!
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(31): error C2065: 'CmdAritmetice' : undeclared identifier
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(31): error C2062: type 'int' unexpected
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(37): error C2065: 'cmd1' : undeclared identifier
d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(37): error C2228: left of '.Execute' must have class/struct/union
type is ''unknown-type''
Edit
If i modify CmdAritmetice <int, Suma> cmd1("+"); with UI::CmdAritmetice<Calcule::Suma<int>> cmd1("+"); the following errors appear when try to compile:
1>d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(32): error C2440: 'specialization' : cannot convert from 'T (__cdecl *)(T,T)' to 'int (__cdecl *)(int,int)'
1> None of the functions with this name in scope match the target type
1>d:\files\visual studio 2010\projects\calculator\aplicatie.cpp(39): error C2660: 'Calculator::UI::CmdAritmetice<Operatie>::Execute' : function does not take 1 arguments
1> with
1> [
1> Operatie=0x0
1> ]
Main.cpp
#include "aplicatie.h"
using namespace Calculator;
int main()
{
Aplicatie app;
app.Run();
return 0;
}
aplicatie.cpp edited
#include <iostream>
#include "aplicatie.h"
#include "Calcule\operatii.h"
#include "UI\cmdaritmetice.h"
using namespace std;
namespace Calculator{
(...)
void Aplicatie::Run()
{
TestSuma();
CmdAritmetice <int, Suma> cmd1("+"); //here i have errors
cmd1.Execute("Introduceti doua numere intregi (x, y)");
}
void Aplicatie::TestSuma()
{
int x = 10, y = 20;
int r = Calcule::Suma(x,y);
}
}
cmdaritmetice.h
#ifndef ARITMETICE_H
#define ARITMETICE_H
#include "UI\comanda.h"
namespace Calculator{
namespace UI{
template<int Operatie(int, int)>
class CmdAritmetice : public ComandaCalcule
{
public:
CmdAritmetice(const string &nume) : ComandaCalcule(nume)
{
}
void Execute()
{
cout << Nume() << endl;
cout << "Introduceti doua numere intregi (x, y)\n";
int x, y;
cin >> x >> endl;
cin >> y >> endl;
cout << x << " " << Nume() << " " << y << " = " << Operatie (x,y) <<endl;
}
};
}
}
#endif
LE
**operatii.h**
#ifndef OPERATII_H
#define OPERATII_H
namespace Calculator{
namespace Calcule{
template<typename T>
T Suma(T x, T y)
{
return x + y;
}
}
#endif
CmdAritmetice is defined in namespace Calculator::UI while Aplicatie is defined in namespace Calculator. So, you must refer to CmdAritmetice as UI::CmdAritmetice within the Calculator namespace.
As for error saying Suma cannot be found, you haven't posted the definition of Suma, so it's hard to say what's going on there, but check to make sure that that too isn't defined within some nested namespace.
EDIT:
The definition for CmdAritmetice is
template<int Operatie(int, int)>
class CmdAritmetice : public ComandaCalcule
{
// ...
};
So it takes a template argument that is function with the signature int(int, int), i.e. a function that accepts 2 ints and returns an int. Within Aplicatie::Run() you try to instantiate the class as
CmdAritmetice <int, Suma>
Obviously this will not work, the template argument needs to be a function matching the signature you've specified in the definition. Also, references to Suma need to be qualified as Calcule::Suma.
I think what you intend to do is
UI::CmdAritmetice<Calcule::Suma<int>> cmd1("+");

C++ Error in program compiling

Why is this c++ program giving me errors:
#include <iostream>
using namespace std;
int main (){
NumbersClass num;
num.setNumbers(1);
}
class NumbersClass
{
public:
NumbersClass() {}
void setNumbers(int i) { }
};
Here are my errors:
taskbcplus.cpp(7): error C2065: 'NumbersClass' : undeclared identifier
taskbcplus.cpp(7): error C2146: syntax error : missing ';' before identifier 'num'
taskbcplus.cpp(7): error C2065: 'num' : undeclared identifier
taskbcplus.cpp(9): error C2065: 'num' : undeclared identifier
taskbcplus.cpp(9): error C2228: left of '.setNumbers' must have class/struct/union
1> type is ''unknown-type''
You need to put the NumberClass definition before the point at which you first instantiate it, i.e. before main.
class NumbersClass
{
public:
NumbersClass() {}
void setNumbers(int i) { }
};
int main (){
NumbersClass num;
num.setNumbers(1);
}

C++: std::initializer_list<T> as first argument in constructor causes compilation error

I was playing around with initializer lists and noticed some inconsistencies. Using an initializer_list as the first argument in a constructor causes a compilation error, but this doesn't happen for functions and member functions, or when other arguments precede the initializer_list.
This code illustrates what I mean:
#include <initializer_list>
using namespace std;
struct A
{
A(initializer_list<int> list){}
A(int a, initializer_list<int> list){}
A(initializer_list<int> list, int b){}
A(int a, initializer_list<int> list, int b){}
};
void B(initializer_list<int> list){}
void B(int a, initializer_list<int> list){}
void B(initializer_list<int> list, int b){}
void B(int a, initializer_list<int> list, int b){}
int main(int argc, char** argv)
{
// Ok
A a = {1};
A b(1, {2});
A c(1, {2}, 3);
B({1});
B(1, {2});
B({1}, 2);
B(1, {2}, 3);
// Error
A d({1});
A e({1}, 2);
return 0;
}
And the build output:
1>------ Build started: Project: Linal (Microsoft Visual C++ Compiler Nov 2012 CTP), Configuration: Release2 x64 ------
1> 'Microsoft Visual C++ Compiler Nov 2012 CTP' is for testing purposes only.
1> main.cpp
1>main.cpp(30): error C2059: syntax error : '{'
1>main.cpp(30): error C2059: syntax error : ')'
1>main.cpp(31): error C2059: syntax error : '{'
1>main.cpp(31): error C2143: syntax error : missing ';' before '}'
1>main.cpp(31): error C2143: syntax error : missing ')' before ';'
1>main.cpp(31): error C2059: syntax error : '}'
1>main.cpp(31): error C2059: syntax error : ')'
1>main.cpp(33): error C2059: syntax error : 'return'
1>main.cpp(34): error C2059: syntax error : '}'
1>main.cpp(34): error C2143: syntax error : missing ';' before '}'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Is this correct behaviour? If so, why does this happen?

"undeclared identifier" is actually declared

I've been getting error C2065s for variables that I've declared in the class header file as public data members, one int and one pointer to that int. The lines of code being flagged as erroneous are only when I use these variables in a function - within the class' constructor, they appear to get through okay.
I'm using Visual Studio 2010 Express to write normal C++ (not Visual C++), and here's the output of the compiler's error log:
1>------ Build started: Project: Project 2, Configuration: Debug Win32 ------
1> BaseClassWithPointer.cpp
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(27): error C2065: 'q' : undeclared identifier
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(27): error C2541: 'delete' : cannot delete objects that are not pointers
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(32): error C2065: 'num' : undeclared identifier
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(33): error C2065: 'q' : undeclared identifier
1>d:\libraries\documents\school\advanced c++\project 2\project 2\baseclasswithpointer.cpp(34): error C2065: 'q' : undeclared identifier
1> Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Finally, here're my code blocks and headers:
BaseClassWithPointer.h
#pragma once
#include <iostream>
using namespace std;
class BaseClassWithPointer
{
public:
int num;
int *q;
BaseClassWithPointer();
BaseClassWithPointer(int value);
BaseClassWithPointer(const BaseClassWithPointer& otherObject);
void destroyPointer();
virtual void print();
virtual ~BaseClassWithPointer(); //Destructor is virtual so that derived classes use their own version of the destructor. ~ (2. Inheritance - base class with pointer variables – destructors.)
const BaseClassWithPointer& operator= (const BaseClassWithPointer &rhs); //Assignment operator is overloaded to avoid shallow copies of pointers. ~ (3. Inheritance – base class with pointer variables – assignment operator overloading.)
};
BaseClassWithPointer.cpp
#pragma once
#include "BaseClassWithPointer.h"
#include <iostream>
using namespace std;
BaseClassWithPointer::BaseClassWithPointer()
{
num = 0;
q = &num;
}
BaseClassWithPointer::BaseClassWithPointer(int value)
{
num = value;
q = &num;
}
BaseClassWithPointer::BaseClassWithPointer(const BaseClassWithPointer& otherObject)
{
num = otherObject.num;
q = &num;
}
void destroyPointer()
{
delete q;
}
void print()
{
cout << "Num: " << num << endl;
cout << "Value pointed to by q: " << *q << endl;
cout << "Address of q: " << q << endl;
}
BaseClassWithPointer::~BaseClassWithPointer()
{
destroyPointer();
}
const BaseClassWithPointer& BaseClassWithPointer::operator=(const BaseClassWithPointer &rhs)
{
if (this != &rhs)
{
num = rhs.num;
q = &num;
}
return *this;
}
You forgot the Class identifier for your destroyPointer() method.
Try
void BaseClassWithPointer::destroyPointer()
instead
This:
void destroyPointer()
...
void print()
Should be
void BaseClassWithPointer::destroyPointer()
{
....
}
void BaseClassWithPointer::print()
{
....
}
etc.
The function destroyPointer() is not part of the class in the cpp file.
It should be:
void BaseClassWithPointer::destroyPointer()
{
delete q;
}
but is:
void destroyPointer()
{
delete q;
}
This is why it cannot find q