题目:
int main() {
Integer a, b;
cin >> a >> b;
cout << a << " " << b << endl;
link(a, b);
a -= 100;
cout << a << " " << b << endl;
b += a;
cout << a << " " << b << endl;
}
以上是主程序,需要写个名为Integer的类使得main函数能正常执行。
EXAMPLE INPUT
1000 2000EXAMPLE OUTPUT
1000 2000 900 1900 1800 2800
解析:
本题主要考察两个点,一个是对于几个操作符的重载,另一个就是对于link函数的实现。我们这里的link先考虑如果只用一个指针来实现,也就是说每个Integer对象只能和一个相关联。
#include <iostream>
#include <vector>
using namespace std;
class Integer{
private:
int value;
int iflinked;
Integer* linked;
public:
Integer(){
value = 0;
iflinked = 0;
}
int getValue() const{
return this->value;
}
void setValue(int x){
this->value = x;
}
void operator -=(int n){
this->value -= n;
if(iflinked)
this->linked->value -= n;
}
void operator +=(Integer & x){
this->value += x.value;
if(iflinked)
this->linked->value += x.value;
}
friend void link(Integer & a, Integer & b);
};
void link(Integer & a, Integer & b){
a.linked = &b;
a.iflinked = 1;
b.linked = &a;
b.iflinked = 1;
}
istream & operator >> (istream & in, Integer & x){
int n;
in >> n;
x.setValue(n);
return in;
}
ostream & operator << (ostream & out, const Integer & x){
out << x.getValue();
return out;
}
这里的set函数和get函数是为了类外面的输入输出操作符能够访问private变量而存在的;link声明为友元函数也是为了写在外面能够访问private变量。
另外,输入输出操作符在operator前必须加引用&,这是c++的规定,用std::ifstream,std::ofstream作为函数参数传递时,必须通过引用传递,因为其copy方法被私有化,从而保证对象的唯一性。
不然会报错:
error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private。
拓展:
那么能否实现可以关联多个变量呢,这里就用到了存放指针的vector。
#include <iostream>
#include <vector>
using namespace std;
class Integer{
private:
int value;
int linkedNumber;
vector<Integer*> linked;
public:
Integer(){
value = 0;
linkedNumber = 0;
}
int getValue() const{
return this->value;
}
void setValue(int x){
this->value = x;
}
void operator -=(int n){
this->value -= n;
if(linkedNumber){
int i;
for(i = 0; i < linkedNumber; i++)
this->linked[i]->value -= n;
}
}
void operator +=(Integer & x){
this->value += x.value;
if(linkedNumber){
int i;
for(i = 0; i < linkedNumber; i++)
this->linked[i]->value += x.value;
}
}
friend void link(Integer & a, Integer & b);
};
void link(Integer & a, Integer & b){
a.linked.push_back(&b);
a.linkedNumber++;
b.linked.push_back(&a);
b.linkedNumber++;
}
istream & operator >> (istream & in, Integer & x){
int n;
in >> n;
x.setValue(n);
return in;
}
ostream & operator << (ostream & out, Integer & x){
out << x.getValue();
return out;
}
int main() {
Integer a, b, c;
cin >> a >> b >> c;
cout << a << " " << b << " " << c << endl;
link(a, b);
link(a, c);
a -= 100;
cout << a << " " << b << " " << c <<endl;
b += a;
cout << a << " " << b << " " << c <<endl;
}
存放指针的vector就正常使用的就好。但是这里是实现的关联依然不具有传递性,如果想要具有传递性,恐怕还要有一个函数将所有关联的变量同步,依然很简单,就不再赘述了。