C++ error C2662 or how to declare in right way - c++

i get the fallowing error when i compile program:
vandenynas.cpp(19) error C2662: 'skaiciavimas::showst' : cannot convert 'this' pointer from 'const skaiciavimas' to 'skaiciavimas &'
there is my classes:
first.h
#pragma once
#include <iostream>
#include <string>
#include "skaiciavimas.h"
using namespace std;
class vandenynas
{
public:
void duomenys (int i, int a, int a0) const;
string GetName()const;
protected:
skaiciavimas sk;
};
first.cpp
#include "vandenynas.h"
skaiciavimas::v vektorV;
void vandenynas::duomenys (int i, int a, int a0) const
{
switch (i)
{
case 0:
vektorV.x=a-a0;
break;
case 1:
vektorV.y=a-a0;
break;
default:
vektorV.z=a-a0;
break;
}
sk.showst(vektorV);
}
second where is called function.h
#pragma once
#include <iostream>
#include <string>
using namespace std;
class skaiciavimas
{
public:
struct v
{
int x;
int y;
int z;
};
void showst(v st);
};
.cpp
#include "skaiciavimas.h"
void skaiciavimas::showst(v st)
{
cout<<st.x<<" "<<st.y<<" "<<st.z<<endl;
}
can someone tel where is mistake?

The problem is that you declare vandenynas::duomenys as a const function, i.e. it does not change anything in the object. But it calls skaiciavimas::showst which is not declared as const, which is not permissible. If you declare one method as const, all methods it calls, in itself or an object that is a member of the object, also have to be declared as const.

skaiciavimas::showst is not a const member function. Since vandenynas::duomenys is a const member function, all members of this are considered const and therefore skaiciavimas::showst cannot be called.

Related

Why my random function always not undeclared?

I'm writing my code on linux . But g++ always tells me"Use of undeclared identifier 'random'".I don't know why I have declare it in "Myvector.h"
my code is like :
Myvector.h
class MyVector {
private:
std::vector<double> data;
const int N;
static bool _bDim;
public:
MyVector(); //默认初始化
MyVector(int a); //设置维度初始化
MyVector(std::initializer_list<double> list);
~MyVector();
double &operator[](int);
MyVector &operator=(const MyVector a) {
MyVector b(outN(a));
this->data = a.data;
return *this;
};
friend MyVector random(int a);
}
#endif // MYVECTOR_H_
Myvector.cpp
#include "Myvector.h"
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
bool MyVector::_bDim = true;
MyVector::MyVector() : N(3) {
data = vector<double>(N, 0.0);
_bDim = false;
};
MyVector::MyVector(int a) : N(a) {
data = vector<double>(N, 0.0);
_bDim = false;
};
MyVector::MyVector(std::initializer_list<double> list) : N(list.size()) {
for (auto i = list.begin(); i != list.end(); i++) {
data.push_back(*i);
}
};
MyVector::~MyVector(){
};
double &MyVector::operator[](int i) { return data[i]; }
MyVector random(int a){
MyVector u(a);
srand(time(NULL));
for(int i=0;i<a;i++){
u[i]=rand();
}
return u;
}
main.cpp
#include "Myvector.h"
#include <iostream>
#include<cstdlib>
#include<math.h>
#include <time.h>
using namespace std;
int main(){
MyVector z=random(1);
return 0;}
In fact ,I just know nothing about it. Is there someone going to help me?Thank you.
Below is nothing meaningful. I just need more words to ask this problem.
In the main function of the main.cpp file the following function is called:
MyVector z=random(1);
This appears to be a function which takes a single int argument. Additionally, there is such a function defined in the Myvector.cpp but not declared in Myvector.h (i.e., the main.cpp file does not see any function declaration for the definition).
Update the Myvector.h header to declare the MyVector random(int a) function. Also, the friend declaration is for a random function with 2 parameters, which doesn't look right.
You have to declare the function random somewhere, e.g.
#include "Myvector.h"
#include <iostream>
#include<cstdlib>
#include<math.h>
#include <time.h>
using namespace std;
MyVector random(int);
int main(){
MyVector z=random(1);
return 0;
}
The problem is random in your main function. That one is not declared.
Declaring a friend function means that function has access to the class as if it were a method. It doesn't declare the function at any time, just allows it inside the class.
Your random function is defined is some header file you have included. In your error message you see the return type of random is long int. And you have declared it as MyVector. I am not sure if math.h or time.h have it.
Solution 1: Change the name of your function.
Solution 2: Put your function in a namespace in order to avoid name ambiguity.

Accessing variables from one class to another in C++

I am trying to access a variable declared in class A from class B, without using static variables. I have the classes separated in header and source files.
I have seen different people using pass by reference (I assume "const &a" declared in the class definition) but it doesn't work for me.
Update:When I tried to pass in the A object to the B::print as a const-reference parameter I got an error. In my example, I am trying to access string a from the function void print declared in class B. The problem now is that I am getting an error in B.cpp.
main.cpp
#include <iostream>
#include <string>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
A first;
B second;
second.print(cout, first);
return 0;
}
A.h
#include <string>
using namespace std;
class A
{
string a = "abc";
public:
A();
void print(ostream& o) const;
~A();
};
A.cpp
#include <iostream>
#include <string>
#include "A.h"
#include "B.h"
using namespace std;
A::A()
{
}
A::~A()
{
}
void A::print(ostream& o) const
{
o << a;
}
ostream& operator<<(ostream& o, A const& a)
{
a.print(o);
return o;
}
B.h
#include <iostream>
#include <string>
#include "A.h"
using namespace std;
class B
{
public:
B();
void print(ostream&, A const&) const;
~B();
};
B.cpp
#include "B.h"
#include "A.h"
#include <iostream>
#include <string>
using namespace std;
B::B()
{
}
B::~B()
{
}
void B::print(ostream& o, A const& a) const
{
o << a << endl;
//^^ error no operator "<<" mathes these operands
}
Since a is not a static member, it can't be accessed without an instance of class A. You can, however, pass one in the function:
class B {
void print(const A &o) {
cout << o.a << endl;
}
};
In addition, if a member is private, you can declare class B as friend, which means it can access private and protected members of class A.
class A {
friend class B;
private:
std::string a = "abc";
};
The way I'd do it is to pass in the A object to the B::print as a const-reference parameter. I'd also pass in the ostream as a reference parameter. And I'd take advantage of C++'s streaming output operator (<<).
Like this:
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::ostream;
using std::string;
class A
{
std::string s = "abc";
public:
void print(ostream& o) const;
};
void A::print(ostream& o) const
{
o << s;
}
ostream& operator<<(ostream& o, A const& a)
{
a.print(o);
return o;
}
class B
{
public:
void print(ostream&, A const&) const;
};
void B::print(ostream& o, A const& a) const
{
o << a << endl;
}
int main()
{
A first;
B second;
second.print(cout, first);
}
UPDATE: given the comments above, I'm not not sure if the problem is "How does one split up code into separate .h and .cpp files?" or if it is "How do I access A member variables from B, without using static variables in A?"
UPDATE: I changed A's member variable from a to s to disambiguate from other a identifiers.

how transfer function from template class

#include <iostream>
#include <windows.h>
#include <string.h>
#include <functional>
#include <stdint.h>
#include <stdio.h>
using namespace std;
template <typename T>
class someclass {
public:
T value;
int sum(int vl1, int vl2) { return vl1 + vl2; };
};
template <typename T>
class someclass2 {
public:
T value;
void print(const std::function<int(int, int)>& func) {
cout << func(3, 4) << '\n';
};
};
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
obj2.print(obj1.sum);
}
Compiler show error on last line : error C3867: 'someclass::sum': non-standard syntax; use '&' to create a pointer to member
Note that
int sum(int vl1, int vl2) { return vl1 + vl2; };
doesn't use its owner class' member in any way, it safely can be declared static, in that case this code would work.
The problem with this code is that a member function got a different type from standalone function. It's a member of class someclass, so its type is int (someclass::*)(int, int) and to call it you need an instance of that class.
The literal solution in general case is to hide pass of this inside the functor created by lambda expression:
obj2.print( [&](int a, int b)-> int { return obj1.sum(a,b); } );
You can use std::bind to do that
int main(int argc, const char **argv)
{
someclass<int> obj1;
someclass2<int> obj2;
using namespace std::placeholders;
obj2.print(std::bind(&someclass<int>::sum, &obj1, _1, _2));
}

Data "member not declared in this scope"

I'm trying to create a vector which will store objects. I have added to the header file of the class as a private data member.
I am trying to initialize this vector as being empty (so that I can add objects to it later on in the program) but when I compile this program to test, this error is returned:
...error: '_bookingVector' was not declared in this scope|
I think the problem is with my initialization list on my default constructor(_bookingVector is obviously the vector):
Schedule::Schedule() : _bookingVector()
{ }
Is my syntax wrong? Or are vectors initialized differently?
Here is my code:
Schedule.h
#ifndef SCHEDULE_H
#define SCHEDULE_H
#include "Booking.h"
#include <vector>
using namespace std;
class Schedule
{
public:
Schedule();
void AddBooking(int bday, int btime, int btrainer, int bid);
void RemoveBooking(int bday, int btime);
void DisplaySchedule();
void DisplayAvailableTimeSlots();
//For Testing
void DisplayDebug();
private:
vector<Booking> _bookingVector;
};
#endif // SCHEDULE_H
Schedule.cpp
#include "Schedule.h"
#include "Booking.h"
#include <vector>
#include <iostream>
Schedule::Schedule() : _bookingVector()
{ }
void AddBooking(int bday, int btime, int btrainer, int bid){
Booking bookingObject(bday, btime, btrainer, bid);
_bookingVector.push_back(bookingObject);
}
void DisplayDebug(){
for(int i = 0; i < _bookingVector.size(); ++i){
cout << _bookingVecotr[i] << endl;
}
}
I'm very eager to learn what I'm doing wrong and fix it.
The issue is not with the constructor, which looks fine if unnecessary1. The issue is that you have defined AddBooking and DisplayDebug as non-member functions, but these should be members in order to access other members of the class.
Modify the definitions to be in the scope of the Schedule class thus:
void Schedule::AddBooking(int bday, int btime, int btrainer, int bid) { ...
^^^^^^^^^^
void Schedule::DisplayDebug(){ ...
^^^^^^^^^^
Also, don't say using namespace std in a header file (I'd go further and say don't say it anywhere but there isn't universal agreement on that.)
1 Your default constructor does not do anything that the compiler-generated one wouldn't do. You can safely remove it.

error undefined reference to .. c++? [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 9 years ago.
so I have a class x that is being used by class y and it's also going to be used by other classes.
.h for class x
#pragma once
#include <string>
#ifndef X_H
#define X_H
class x
{
public:
x();
const std::string & getName() const;
int getQuantity();
private:
std::string name;
int quantity;
};
#endif
.cpp for x
#include <string>
#include "x.h"
using namespace std;
x::x()
: name(),quantity(0)
{
}
const string & x::getName() const
{
return name;
}
const string & x::getQuantity() const
{
return quantity;
}
this is the .h for class y
#pragma once
#include <string>
#include <array>
#include "x.h"
class y
{
public:
static const size_t number = 20;
y();
float getTotal();
private:
std::array<X*, number> arrayList;
};
and this is the .cpp for class y
#include "y.h"
#include "x.h"
#include <array>
#include <string>
#include <iostream>
using namespace std;
y::y()
: arrayList()
{
}
float y::getTotal()
{
float total=0.0;
for(int i=0; i< number; i++)
{
if(arrayList[i] != nullptr)
{
total += arrayList[i]->getQuantity();
}
}
}
methods in the y class uses an array of pointers to method y and I'm trying to use some methods from class x using the array members but I get an error saying:
undefined reference to `x::x(...)
I think it has something to do with the preprocessors or the headers.
This means that you forgot to define the default constructor X::X() or some other constructor with parameters ( what does x::x(...) mean?) of class X. You only declared it in the class definition.
Or the other reason is that the module with the constructor definition was not included in the project build.
In class x you have explicitly declared the default constructor x() but you have not defined it. If you want to use the default constructor, remove its definition or define it with x::x():name(std::string()),quantity(0){}