I have the following piece of code:
class Student {
public:
Student(){}
void display() const{}
friend istream& operator>>(istream& is, Student& s){return is;}
friend ostream& operator<<(ostream& os, const Student& s){return os; }
};
int main()
{
Student st;
cin >> st;
cout << st;
getch();
return 0;
}
I have tried myself when omitting the friend keywords to make the operators become the member function of the Student class, then the compiler would produce "binary 'operator >>' has too many parameters". I have read some document saying that happened because all member functions always receive an implicit parameter "this" (that's why all member functions can access private variables).
Based on that explanation, I have tried as follows:
class Student {
public:
Student(){}
void display() const{}
istream& operator>>(istream& is){return is;}
ostream& operator<<(ostream& os){return os; }
};
int main()
{
Student st;
cin >> st;
cout << st;
getch();
return 0;
}
And got the error message: "error C2679: binary '>>' : no operator found which takes a right-hand operand of type 'Student' (or there is no acceptable conversion)"
Can anyone give me a clear explanation, please?
You can't say that the function is a friend function, and then include the function in-line. The friend keyword implies that the function is not defined in the class, but it can access all the private and protected variables of the class. Change your code to:
class Student {
public:
Student(){}
void display() const{}
friend istream& operator>>(istream& is, Student& s);
friend ostream& operator<<(ostream& os, const Student& s);
};
istream& operator >>(istream& is, Student& s) { return is; }
ostream& operator <<(ostream& os, const Student& s) { return os; }
Look at http://www.java2s.com/Code/Cpp/Overload/Overloadstreamoperator.htm for another example.
With << and >>, the left hand operand is always a file stream, so you cannot overload them within your actual class (it'd technically have to go in the file stream class).
I forget where that operator is defined, but it would either be the global operator>>, or the operator belonging to the stream.
Defining it in Student is the wrong place.
Related
I would like to assign a name to a thread, the thread itself must do this. The thread is a class member of the class foo.
I would like to start this thread with a lambda but unfortunately I get the error message:
no match for call to '(std::thread) (foo::start()::<lambda()>)
Can someone explain to me where the problem is?
Previously I had created a temporary thread object, and put this with move on the thread "manage", however, I can then give no name.
class foo {
public:
int start()
{
this->manage([this](){
auto nto_errno = pthread_setname_np(manage.native_handle(),"manage"); // Give thread an human readable name (non portable!)
while(1){
printf("do work");
}
});
return 1;
}
private:
int retVal;
std::thread manage;
};
You passed the lambda in a wrong way, after initialization the manage thread can't be initialized again. you should create a new std::thread and assign it.
the following compiles and indeed prints "manage".
class foo {
public:
int start()
{
manage = std::thread([this]{
auto nto_errno = pthread_setname_np(manage.native_handle(),"manage");
char name[16];
pthread_getname_np(pthread_self(), &name[0], sizeof(name));
cout << name << endl;
});
manage.join();
return 1;
}
private:
int retVal;
std::thread manage;
};
I am attempting to create template classes where each can solve a specific facet of the problem so to be able to mishmash them without resorting to creating the traditional abstract virtual classes.
For that, I believe CRTP would be the best paradigm.
However, when using CRTP a bit more I found trapped on this weak resolution logic - compiler (g++ 4.8.2) cannot distinguish between two methods on different classes even though their signature is different - only the method name is the same.
The classes implementation:
template< class T >
class A {
public:
void foo( uint32_t val ) {
T* me = static_cast<T*>( this );
me->doit();
}
};
template< class T >
class B {
public:
void foo() {
uint32_t v32 = 10;
T* me = static_cast<T*>( this );
me->foo( v32 );
}
};
class Derived : public A<Derived>,
public B<Derived>
{
public:
void doit() {
std::cout << "here" << std::endl;
}
};
Then it is used as
Derived d;
d.foo();
When compiled, this error surfaces:
$ g++ -std=c++11 -c testLambda.cpp
testLambda.cpp: In function ‘int main(int, char**)’:
testLambda.cpp:102:7: error: request for member ‘foo’ is ambiguous
d.foo();
^
testLambda.cpp:25:10: note: candidates are: void B<T>::foo() [with T = Derived]
void foo() {
^
testLambda.cpp:16:10: note: void A<T>::foo(uint32_t) [with T = Derived; uint32_t = unsigned int]
void foo( uint32_t val ) {
Is this a compiler bug or the actual expected result?
User pubby8 at reddit.com/r/cpp responded (quote) a quick fix is to add this to Derived's class body:
using A<Derived>::foo;
using B<Derived>::foo;
I have some homework, and I have troubles understanding, (probably) how passing parameters to std::thread constructor works.
Assume following code (I deleted unneeded parts)
template<typename T, typename Task>
class Scheduler
{
private:
typedef std::unordered_map<std::size_t, T> Results;
class Solver
{
public:
Solver(Task&& task) : m_thread(&Solver::thread_function, std::move(task))
{
m_thread.detach();
}
Solver(Solver&& solver) = default; // required for vector::emplace_back
~Solver() = default;
private:
void thread_function(Task&& task)
{
task();
}
std::thread m_thread;
};
public:
Scheduler() = default;
~Scheduler() = default;
void add_task(Task&& task)
{
m_solvers.emplace_back(std::move(task));
}
private:
std::vector<Solver> m_solvers;
};
template<typename T>
struct Ftor
{
explicit Ftor(const T& t) : data(t) { }
T operator()() { std::cout << "Computed" << std::endl; return data; }
T data;
};
int main()
{
Scheduler<int, Ftor<int>> scheduler_ftor;
Scheduler<int, std::function<int(void)>> scheduler_lambda;
Ftor<int> s(5);
scheduler_ftor.add_task(std::move(s));
scheduler_lambda.add_task([](){ std::cout << "Computed" << std::endl; return 1; });
}
Why it doesn't compile?
MVS2015 is complaining about
functional(1195): error C2064: term does not evaluate to a function taking 1 arguments
functional(1195): note: class does not define an 'operator()' or a user defined conversion operator to a pointer-to-function or reference-to-function that takes appropriate number of arguments
note: while compiling class template member function 'Scheduler<int,Ftor<int> >::Solver::Solver(Task &&)'
While G++ 4.9.2
functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (Scheduler<int, Ftor<int> >::Solver::*)(Ftor<int>&&)>(Ftor<int>)>’:
required from ‘void Scheduler<T, Task>::add_task(Task&&) [with T = int; Task = Ftor<int>]’
functional:1665:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (Scheduler<int, Ftor<int> >::Solver::*)(Ftor<int>&&)>(Ftor<int>)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
I suppose there are some problems with std::moving to std::thread.
If you use member function as first thread argument, second argument supposed to be this pointer, pointing to the object to which member function could be called to
UPDATE
Good discussion here
Start thread with member function
I don't follow your code, but addressing the question, a extrapolated answer will be( most of the code is psuedocode)
lets assume that there is a function int test(int name).
thread t0;
t0 = thread(test,32);
thread t1(test,43);
Passing a argument to function.
int temp = 0;
int testfunc(int& q)
{
cout<<q;
}
thread t1;
t1 = thread(testfunc,ref(temp));
In short, you just pass the name of the function that must be run in the thread as the first argument, and the functions parameters follow it in same order as they are in the function definition, for passing by reference you can use the ref() wrapper.See the below example.
#include <iostream>
#include <thread>
#include <string>
using namespace std;
void test(int a,int &a,string test)
{
\\do something
}
int main()
{
int test1 = 0;
string tt = "hello";
thread t1;
t1 = thread(23,&test1,tt);
t1.detach();
return 0;
}
if you are wondering about the use of join() and detach(), refer to this thread: When should I use std::thread::detach?, refer to my answer post in that thread.
I have a question concerning working with classes in c++. I must say I'm a beginner. For example, i have this class:
class student {
private:
char* name;
public:
int nrcrt;
student() {
name = new char[7];
name = "Anonim";
nrcrt = 0;
}
student(char* n, int n) {
this->name = new char[7];
strcpy(name, n);
nrcrt = nr;
}
~student() {
delete [] name;
}
char* get_name() {
return this->name;
}
}
void main() {
student group[3];
group[0] = student("Ana", 1);
group[1] = student("Alex", 2);
group[2] = student("Liam", 5);
for (i=0; i<3; i++) {
if (group.nrcrt[i] != 0)
cout << group[i].get_name() << Endl;
}
}
My question is why is it displaying different characters?
first of all your code is not working.
3.cpp:40:18: error: request for member ‘nrcrt’ in ‘group’, which is of non-class type ‘student [3]’
if(group.nrcrt[i]!=0)
i is also not declared.please make proper changes.
group.nrcrt[i]
should be changed to:
group[i].nrcrt
When the array is created, your default constructor is used.
When you assign to the elements, your destructor is called, deleting name.
The default constructor is assigning a literal to name, and deleting that memory has undefined behaviour.
In your default constructor, replace
name = "Anonim";
with
strcpy(name, "Anonim");
Your compiler should have warned you about the assignment.
If it didn't, increase the warning level of your compiler.
If it did, start listening to your compiler's warnings.
do not worry. C++ could look a bit scary as first but it is ok when you get into it. First, let's say that all classes it is good to start with upper case letters. Secondly, you have two constructors (default without parameters and one or more with, in our case one). Default consructor you need to declare an array of objects:
Student group[3];
The next important thing is that you then do not need the rest of the constructors in that case.
group[0]=student("Ana",1);
group[1]=student("Alex",2);
group[2]=student("Liam",5);
Remember to include ; at the end of class declaration. To put all the statements and expression throughout your interation within the same loop. Here is what I found as an errors anf fix them. Could probably have more.
class Student
{
private:
char* name;
public:
int nrcrt;
Student()
{
name=new char[7];
strcpy(name, "Anonim");
nrcrt=0;
}
Student( char* n, int n)
{
this->name=new char[7];
strcpy(name, n);
nrcrt=nr;
}
~Student()
{
delete [] name;
}
char* get_name()
{
return this->name;
}
};
int main()
{
Student group[3];
for(int i=0;i<3;i++)
{
if(group.nrcrt[i]!=0)
cout<<group[i].get_name()<<endl;
}
return 0;
}
I have the following code:
#include "iostream"
#include "conio.h"
using namespace std;
class Student {
private:
int no;
public:
Student(){}
int getNo() {
return this->no;
}
friend istream& operator>>(istream& is, Student& s);
friend ostream& operator<<(ostream& os, const Student& s);
};
ostream& operator<<(ostream& os, const Student& s){
os << s.getNo(); // Error here
return os;
}
int main()
{
Student st;
cin >> st;
cout << st;
getch();
return 0;
}
When compiling this code, the compiler produced the error message: "error C2662: 'Student::getNo' : cannot convert 'this' pointer from 'const Student' to 'Student &'"
But if I made the no variable public and change the error line like: os << s.no; then things worked perfectly.
I do not understand why this happened.
Can anyone give me an explanation, please?
Thanks.
Because s is const in that method, but Student::getNo() isn't a const method. It needs to be const.
This is done by changing your code as follows:
int getNo() const {
return this->no;
}
The const in this position means that this entire method does not change the contents of this when it is called.