#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Course
{
public:
string name;
string instructorInCharge;
int numberOfStudents;
int totalMarks;
Course(string u, string v, int p, int q){
this->name=u;
this->instructorInCharge=v;
this->numberOfStudents=p;
this->totalMarks=q;
}
vector<int> studentMarks (numberOfStudents);
};
class Labs:public Course
{
vector<int>labMarks(numberOfStudents);
};
int main()
{
Course c("Rahul","Hota",200,300);
cout<<"hello there";
}
When I compile this code I’m getting the following error:
1.cpp:20:31: error: 'numberOfStudents' is not a type
20 | vector<int> studentMarks (numberOfStudents);
| ^~~~~~~~~~~~~~~~
1.cpp:28:29: error: 'numberOfStudents' is not a type
28 | vector<int>labMarks(numberOfStudents);
| ^~~~~~~~~~~~~~~~
Please tell me what my mistake is.
numberostudents was supposed to be the size of the vector. But not any function.
vector<int> studentMarks (numberOfStudents);
This is a function declaration. The return type is vector<int>, the name is studentMarks and it accepts a single parameter of type numberOfStudents. Except, as the error points out, numberOfStudents is not a type.
You cannot use parentheses to specify a default member initialiser. You have to either use curly braces:
T member {value};
or "equals" initialiser:
T member = value;
Note however, that you don't initialise numberOfStudents member, but rather assign it later in the constructor body. This assignment is after studentMarks has been initialised, and thus the default member initialiser of studentMarks won't reflect the size that was assigned. Rather, the behaviour of the program would be undefined due to the use of an indeterminate value. This can be fixed by initialising numberOfStudents in the member initialiser list.
If you want in-class initialization, you may do this:
vector<int> studentMarks = vector<int>(numberOfStudents);
Now the default constructor will initialize studentMarks with vector<int>(numberOfStudents) when an instance of Course is created.
However, this will cause undefined behavior since numberOfStudents is not initialized before the initialization of studentMarks. You could use the member initalizer list instead:
Course(std::string u, std::string v, int p, int q)
: name(std::move(u)),
instructorInCharge(std::move(v)),
numberOfStudents(p),
totalMarks(q),
studentMarks(numberOfStudents)
{
}
and likewise for the Labs class:
class Labs : public Course {
public:
Labs(std::string u, std::string v, int p, int q)
: Course(u, v, p, q), // initialize the base class part of a `Labs`
labMarks(p) // initialize the added member variable
{
}
std::vector<int> labMarks;
};
You can also use resize method of std::vector.
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Course
{
public:
string name;
string instructorInCharge;
int numberOfStudents;
int totalMarks;
vector<int> studentMarks;
Course(string u, string v, int p, int q){
this->name = u;
this->instructorInCharge = v;
this->numberOfStudents = p;
this->totalMarks = q;
this->studentMarks.resize(numberOfStudents);
}
};
class Labs : public Course
{
vector<int> labMarks;
public:
Labs(string u, string v, int p, int q) : Course(u, v, p, q)
{
labMarks.resize(p);
}
};
int main()
{
Course c("Rahul","Hota",200,300);
cout<<"hello there";
}
Related
I have 2 sample codes below:
#include<iostream>
#include<vector>
using namespace std;
class emp{
int emp_count;
public:
emp(){emp_count=2;}
int get_employee_count() const {return emp_count;}
};
int main(){
const emp e1;
cout<<e1.get_employee_count();
return 0;
}
Above code works fine, however, below code gives an error for trying to change a read-only value:
#include<iostream>
#include<vector>
using namespace std;
class emp{
const int emp_count;
public:
emp(){emp_count=2;}
int get_employee_count() const {return emp_count;}
};
int main(){
emp e1;
cout<<e1.get_employee_count();
return 0;
}
A const class object doesn't let me change the value of the data member, but based on the above example, how is a const class object different from a const data member as I am able to assign the value in the constructor body in the 1st code, while the 2nd code restricts me to do the same?
A const class object doesn't allow the value of any of its data members to be modified outside the constructor. For example:
#include<iostream>
#include<vector>
class emp {
public:
int emp_count; // Made public for demonstration
emp() { emp_count = 2; }
int get_employee_count() const { return emp_count; }
};
int main()
{
const emp e1;
emp e2;
e1.emp_count = 10; // Compiler error
std::cout << e1.get_employee_count();
return 0;
}
But emp_count can still be modified by the constructor:
emp()
{
emp_count = 2; // This is assignment, not initialization
}
A const data member is a data member that cannot be modified after initialization, neither inside the class nor outside the class.
To initialize a data member, just assign a value to it as such:
class emp
{
const int emp_count = 2;
public:
Or initialize it using the constructor as such:
class emp
{
const int emp_count;
public:
emp() : emp_count(2) { } // Initialization of emp_count
int get_employee_count() const { return emp_count; }
};
Also, consider not using the following line in your code:
using namespace std;
..as it's considered as bad practice.
emp_count=2; is not initialization, it is an assignment. Even if it happens in a constructor. And one cannot assign to const objects.
Use the initializer list to initialize const members:
emp(): emp_count(2) {}
Even better is to use in-class initialization for constants:
class emp{
int emp_count=2;
public:
int get_employee_count() const {return emp_count;}
};
This has the advantage of rule-of-zero and it propagates the value to all constructors if any are defined explicitly.
#include <bits/stdc++.h>
using namespace std;
class Graph
{
int V;
public:
Graph(int V)
{
this->V = V;
}
vector<list<int>> adj_list(V);
void add_edge(int u, int v)
{
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}
};
I am trying to make an adjacency list using the Graph class. However I am getting the following error:
member "Graph::V" is not a type name.
I want V to be the size of the vector of lists that I've created.
Please help me figure out my mistake.
You can't magically resize as you're attempting. the adj_list member should be in the initialization list and properly constructed:
class Graph{
int V;
std::vector<std::list<int>> adj_list;
public:
Graph(int v)
: V(v)
, adj_list(v) // <<===== here
{
}
void add_edge(int u, int v){
adj_list[u].push_back(v);
adj_list[v].push_back(u);
}
};
The expression:
vector<list<int>> adj_list(V);
The argument is not correct, you could use the container's initializer list like so:
vector<list<int>> adj_list{V};
But still, V is uninitialized, its value is undefined at the point of construction, as WhozCraig pointed out these both belong in the object initializer list.
How to initialize variable(s) dynamically i.e. being not as constant, in class declaration which will be invoked/used without need of object instantiation such as a constructor for member function call immediately gets returned in a function ?
There must, side by side of that variable(s) in that class, be a constant member.
enum Value :int { NO,LOW,MED,HIGH };
template<Value V> class valuation {
public:
valuation(const ints) : pos(s) {};
valuation(int a, int b, int c) : j(a), k(b), l(c) {};
value() {
if (!V)
return (j+k+l) * pos;
}
private:
const int pos;
int j,k,l;
};
int a_function(int s) {
return valuation<NO>(s).value(); // no need object at all
}
int main() {
// somehow in run-time j, k, l has been given 1,2,3, or other valid values
int v = a_function(7) // e.g.
}
Thanks in advance
I think you want to declare your value method -- or at least a version of it -- as a static member. This will allow you to call the method without instantiating an object from your class.
I've this error when I try to save a number into my vector...
Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript
The code is:
class Elemento{
private:
int Nodo;
public:
Elemento(){};
~Elemento(){};
void SetNumero(int x) { Nodo = x; };
int GetNumero() { return Nodo; };
};
class MagicSquare{
private:
int N;
int Possibili_N;
int Magic_Constant;
vector<Elemento> Square(int Possibili_N);
public:
MagicSquare() { };
~MagicSquare() { };
void Set_N(int x) { N = x; };
void Set_PossibiliN(int x) { Possibili_N = x; };
void Set_MagicConstant(int x) { Magic_Constant = x; };
. . .
void SetSquare(int i, int x) { Square[i].SetNumero(x); }; // got error here
int GetSquare(int i) { return Square[i].GetNumero(); }; // got error here
};
I've got error whenever I use Square[i].method()...
I call a method that pass the index in the Square and the value to put in Elemento->Nodo, but I've to use a public method to access to private Nodo. The same with the GET. I want to get the value for displaying it.
You seem to have declared Square as a function, not a variable.
Instead, declare vector<Elemento> Square; and initialize it in the constructor.
You declared Square as a function, not a variable. So Square[i] is not valid.
Change
vector<Elemento> Square(int Possibili_N);
to
vector<Elemento> Square;
or call it using
Square(i)
if it is actually a function.
If you change it to a variable, you need to be sure to initialize it properly, preferably in the constructor.
Your line vector<Elemento> Square(int Possibili_N); is know as C++ most vexing parse.
Instead of declaring a member variable, as intended, you are declaring a function taking an int and returning a vector.
Instead, setup the member vector (and all other member variables) in the constructor initialization list:
class MagicSquare{
private:
int N;
int Possibili_N;
int Magic_Constant;
vector<Elemento> Square;
public:
MagicSquare( int n, int p, int m ) :
N( n ),
Possibili_N( p ),
Magic_Constant( m ),
Square( p ) {
}
...
I need to create a vector of vectors full of integers. However, I continuously get the errors:
error: expected identifier before numeric constant
error: expected ',' or '...' before numeric constant
using namespace std;
class Grid {
public:
Grid();
void display_grid();
void output_grid();
private:
vector<int> row(5, 0);
vector<vector<int> > puzzle(9, row);
int rows_;
int columns_;
};
You cannot initialize the member variables at the point where you declare them. Use an initialization list in the constructor for that:
Grid::Grid()
: row(5,0), puzzle(9, row),
rows_(5), columns_(9)
{
}
C++ class definitions are limited in that you cannot initialise members in-line where you declare them. It's a shame, but it's being fixed to some extent in C++0x.
Anyway, you can still provide constructor parameters with the ctor-initializer syntax. You may not have seen it before, but:
struct T {
T() : x(42) {
// ...
}
int x;
};
is how you initialise a member, when you might have previously tried (and failed) with int x = 42;.
So:
class Grid {
public:
Grid();
void display_grid();
void output_grid();
private:
vector<int> row;
vector<vector<int> > puzzle;
int rows_;
int columns_;
};
Grid::Grid()
: row(5, 0)
, puzzle(9, row)
{
// ...
};
Hope that helps.
You can't initialize a member in a class declaration unless it's const static, because in C++ no code is being run/generated when you are declaring a class. You'll have to initialize them in your constructor.
You should initialize members in the class constructor, not the declaration. The following doesn't seem to be right in any way:
vector<int> row(5, 0);
vector<vector<int> > puzzle(9, row);
If row and puzzle are functions - the parameters should be types. If they're member variables - initialize them in the class constructor.
You cannot initialize mutable members as a part of class definition itself. Instead do assign it in in the constructor.
// ....
Grid()
{
row.resize(5,0) ;
puzzle.resize(9,row) ;
}
private:
vector<int> row;
vector<vector<int> > puzzle ;
// ..