【发布时间】:2016-03-07 03:20:26
【问题描述】:
抱歉,这是一个如此简单的问题。我一直在使用 tutorialspoint.com 来学习 C++。目前我正在尝试了解类和运算符重载。对于其他成员函数,网站使用此约定
class Box {
private:
int Volume;
public:
Box(int num);
...
}
Box::Box(int num) {
Volume = num;
}
但是,当重载运算符时,他们使用 this
class Box {
private:
int volume;
public:
Box(int num);
Box operator+(const Box &b) {
Box box;
box.volume = this->volume + b.volume;
return box;
}
}
它们在类中定义了重载函数。是否可以在课堂之外定义它?如果是这样,怎么做?我试过了
Box Box::operator+(const Box &b) {...}
Box::Box operator+(const Box &b) {...}
但这些不起作用
我如何在课堂之外做到这一点?
再次抱歉,这是一个如此简单的问题。 谢谢
编辑 我的代码是这样的
#include <iostream>
#include <string>
using namespace std;
class Box {
private:
int volume;
public:
Box(int num);
Box operator+(const Box &b);
};
Box::Box(int num) {
volume = num;
}
Box Box::operator+(const Box &b) {
Box box;
box.volume = this->volume + b.volume;
return box;
}
int main() {
Box one(2);
Box two;
two = one + one;
}
我的错误是
Overloading.cc: In member function 'Box Box::operator+(const Box&)':
Overloading.cc:18:6: error: no matching function for call to 'Box::Box()'
Overloading.cc:18:6: note: candidates are:
Overloading.cc:13:1: note: Box::Box(int)
Overloading.cc:13:1: note: candidate expects 1 argument, 0 provided
Overloading.cc:5:7: note: Box::Box(const Box&)
Overloading.cc:5:7: note: candidate expects 1 argument, 0 provided
Overloading.cc: In function 'int main()':
Overloading.cc:25:6: error: no matching function for call to 'Box::Box()'
Overloading.cc:25:6: note: candidates are:
Overloading.cc:13:1: note: Box::Box(int)
Overloading.cc:13:1: note: candidate expects 1 argument, 0 provided
Overloading.cc:5:7: note: Box::Box(const Box&)
Overloading.cc:5:7: note: candidate expects 1 argument, 0 provided
【问题讨论】:
-
第一个应该没问题。你是什么意思“不工作”?有任何错误信息吗?
-
当您说“这些不起作用”时,您的意思是什么?你有构建错误吗?出乎意料的结果?还有什么?请详细说明,并向我们提供更多详细信息(包括构建错误,如果有的话)。
标签: c++ class overloading