c++中操作符重载的语法是什么?
What is the syntax for Operator Overloading in C++?
我当时正在学习c++,当我编写一个小程序来学习更多关于操作符重载的知识时,程序在主函数中出现了一个错误,我在这里写了"Ponto p1(1,5), p2(3,4), Soma;"。谁能告诉我如何正确使用操作符重载 ?谢谢你!
PS:这个程序是用我的母语葡萄牙语写的,但我想找到我的错误不会有问题。
#include <iostream>
using namespace std;
class Ponto
{
private:
int x,y;
public:
Ponto(int a, int b)
{
x = a;
y = b;
}
Ponto operator+(Ponto p);
};
Ponto Ponto::operator+(Ponto p)
{
int a, b;
a = x + p.x;
b = y + p.y;
return Ponto(a, b);
}
int main(void)
{
Ponto p1(1,5), p2(3,4), Soma;
Soma = p1.operator+(p2);
return 0;
}
你没有默认构造函数,所以当它试图构造Soma
时,你会得到一个错误。
一旦你提供了自己的构造函数,编译器提供的默认构造函数就不再生成了。你要么自己创建,要么给接受参数的构造函数的参数添加默认值。
您应该在适当的位置初始化Ponto Some
,并设置一些值:Ponto Some = p1 + p2;
还应该将"constant reference" - reference to const object
: const Ponto &name
传递给操作符+。
#include <iostream>
using namespace std;
class Ponto {
int x, y;
public:
Ponto(int, int);
Ponto operator+(const Ponto&);
};
Ponto::Ponto(int a, int b) : x(a), y(b) {}; // Use 'initializer list'
Ponto Ponto::operator+(const Ponto &other) {
// Not need to do calculations explicitly
return Ponto(x+other.x, y+other.y);
}
int main() {
Ponto p1(1, 5), p2(3, 4);
// Not need to call operator+ explicitly - it's compiler's work
Ponto Soma = p1 + p2;
return 0;
}
相关文章:
- C++避免重复声明的语法是什么
- 使用基类指针调用基类的值构造函数的语法是什么?
- 这行/语法是什么意思?
- 初始化对象以在 C++08 中作为参数传递的首选语法是什么?
- 将引用绑定到指针的语法是什么?(各种)
- 这个typedef和转换运算符语法是什么意思
- 此语法是什么意思.(::*).
- 将显式指定的函数模板重载作为模板参数传递的正确语法是什么?
- 使用 pybind11 绑定 typedef 类型的正确语法是什么?
- 将此类传递给引用的正确语法是什么?
- 带有约束的可变参数模板的'requires'表达式的语法是什么?
- 在TensorFlow C++中用于feed_dict的语法是什么?
- 调用模板化类内的枚举类枚举器的正确语法是什么
- 返回没有 typedef 的成员函数指针的语法是什么?
- 将强制转换运算符重载到 std::map 的正确语法是什么
- 这种增量语法是什么意思
- 返回结构的方法的正确语法是什么
- C 中的(*)语法是什么意思
- 堆栈(int = 10),这个语法是什么意思(C++)
- variadic模板阵列参考参数的语法是什么?