Effective C++ 24. Declare non-member functions when type convesions should apply to all parameters

class Rational {
public:
    Rational(int numerator = 0, int denominator = 1);
    int numerator() cont;
    int denominator() const;
    const Rational operator*(const Rational& rhs) const;
private:
    ...
};

Rational oneHalf(1, 2);
Rational result;
result = 2 * oneHalf;   // error
class Rational {
public:
    Rational(int numerator = 0, int denominator = 1);
    ...
private:
    ...
};
const Rational operator*(const Rational& lhs, const Rational& rhs) {
    return (lhs.numerator() * rhs.numerator(), rhs.denominator() * rhs.denominator());
}
Rational oneFourth(1, 4);
Rational result;
result = 2 * oneFourth; // it works! (int to Rational is implicit type conversion)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
This error message usually occurs when you try to pass a non-static member function as a callback function to a Qt signal. To solve this issue, you need to ensure that the member function is declared as `static` or that it is a non-member function. If you cannot declare the member function as static, you can use a lambda function or a `std::bind` expression to wrap the member function into a callable object that can be passed as a callback. For example, suppose you have a class `MyClass` with a non-static member function `myFunction`, and you want to connect a signal to this function: ```cpp class MyClass : public QObject { Q_OBJECT public: void myFunction(int value); }; MyClass myObject; connect(mySignal, &MySignal::valueChanged, &myObject, &MyClass::myFunction); // Error! ``` Since `myFunction` is not static, you will get the error message "reference to non-static member function must be called" when you try to compile this code. To solve this, you can wrap `myFunction` into a lambda function: ```cpp class MyClass : public QObject { Q_OBJECT public: void myFunction(int value); }; MyClass myObject; connect(mySignal, &MySignal::valueChanged, &myObject, [](int value){ myObject.myFunction(value); }); // OK! ``` Alternatively, you can use `std::bind`: ```cpp class MyClass : public QObject { Q_OBJECT public: void myFunction(int value); }; MyClass myObject; connect(mySignal, &MySignal::valueChanged, &myObject, std::bind(&MyClass::myFunction, &myObject, std::placeholders::_1)); // OK! ``` Both of these solutions create a callable object that calls `myFunction` on `myObject` with the correct parameter.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值