gpt4 book ai didi

c++ - 重载运算符 [ ] 用作 Polynomial 类的 setter

转载 作者:行者123 更新时间:2023-11-28 01:32:14 25 4
gpt4 key购买 nike

我创建了一个 Polynomial 类,但我想重载索引运算符以用作 setter,例如 myPolyObject[0] = 2.5,但在尝试重载它时出现错误。

class Polynomial
{
public:
Polynomial();
Polynomial(Polynomial&);
Polynomial(double* coefficient, int size);
~Polynomial() { delete [] polynomial ; }
double operator [] (int exponent) const;
friend ostream& operator << ( ostream& , const Polynomial&);
Polynomial& operator = (const Polynomial&);
double evaluate(double x) const;
int getSize() const;
double operator [] (int exponent, double coefficient);
Polynomial& operator + ( Polynomial& );
Polynomial& operator + ( double x );
Polynomial& operator - (Polynomial&);
Polynomial& operator - (double x);
Polynomial& operator * (Polynomial&);
Polynomial& operator * (double x);
private:
double* polynomial;
};

在此代码中,我希望双运算符 [](整数指数, double 系数)为数组获取索引(指数)并将该索引处的值设置为 double 系数值。

最佳答案

你的问题好像想要两个不同的东西,第一位在评论里回答了,返回引用。这是完整性的示例,

struct example
{
double value_[10];
double& operator [] (int index) {
return value_[index];
}
};

int main() {
example e;
e[0] = 2.2;
std::cout << e.value_[0] << std::endl;
}

Demo

然后你说..

I want double operator [] (int exponent, double coefficient) to take an index (exponent) for the array and set the value at that index to the double coefficient value.

你不能有 operator[]有多个参数。有几个选择;接受 std::pair<int,double> ,它的语法非常简洁。例如..

struct example
{
double operator [] (const std::pair<int,double>& values) {
return 2.0;
}
};

int main() {
example e;
e[{1,2.2}];
//or
e[std::make_pair(1,2.2)];
}

Demo

或者如果您真的想要逗号,您可以为指数创建自己的类型并重载逗号运算符。

struct exponent
{
int exp_;
double coeff_;
exponent(int value) : exp_(value),coeff_(0){}

operator std::pair<int,double>() {
return std::make_pair(exp_,coeff_);
}

exponent& operator,(double coeff) {
coeff_ = coeff;
return *this;
}
};

struct example
{
double operator [] (const std::pair<int,double>& values) {
return 2.0;
}
};

int main() {
example e;
e[exponent(1), 3.3];
}

Demo

我个人会选择第一个选项,或者重载 operator()相反。

关于c++ - 重载运算符 [ ] 用作 Polynomial 类的 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51014095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com