使用线程可以覆盖我们需要跨越的功能的重载?
我有一个简单的类叫Complex.
- class Complex
- {
- public:
- Complex():realPart_(0),imagPart_(0){}
- Complex(double rp,double ip) : realPart_(rp),imagPart_(ip) {}
- double & real() { return realPart_;}
- double & imag() { return imagPart_;}
- const double & real() const { return realPart_;}
- const double & imag() const { return imagPart_;}
- double square() const {return realPart_*realPart_ - imagPart_*imagPart_;}
- void display() const
- {
- std::cout << "Square of the Complex number (" << realPart_ << ") + i (" << imagPart_ << " ) is " << square() << std::endl;
- }
- void display(unsigned nTimes) const {while(nTimes-- > 0)display();}
- private:
- double realPart_;
- double imagPart_;
- };
- void Test3()
- {
- Complex c1(1,0.74),c2(2,0.35);
- std::thread sqCalc1(&Complex::display,&c1);
- std::thread sqCalc2(&Complex::display,&c2);
- sqCalc1.join();
- sqCalc2.join();
- }
- error C2661: 'std::thread::thread' : no overloaded function takes 2 arguments
解决方法
问题与std :: thread无关(错误是误导),可以通过重新排列代码来显示:
- auto memfunc = &Complex::display;
- std::thread sqCalc1(memfunc,&c1);
- std::thread sqCalc1(memfunc,&c2);
现在错误将在第一行,因为正如其他答案所说,& Complex :: display表达式是指一个重载的函数,编译器不知道你的意思.
您可以通过向演示者或类似的方式告知编译器要尝试调用的函数的类型来选择所需的重载:
- void (Complex::*memfunc)() const = &Complex::display;
- std::thread sqCalc1(memfunc,&c2);
现在你明确地要求显示重载返回void并且不带参数.
如果您的编译器支持C 11别名声明,则可以使其更容易阅读:
- using memfunc_type = void (Complex::*)() const;
- memfunc_type memfunc = &Complex::display;
- std::thread sqCalc1(memfunc,&c2);