请解释错误在哪里?用评论标记错误。例如,操作过载。
#include <iostream>
#include <conio.h>
using namespace std;
class Counter
{
protected:
int count;
public:
Counter():count(0)
{}
Counter(const int t):count(t)
{}
void get_count()
{
cout << count << endl;
}
Counter operator + (Counter t2)
{
return (this->count + t2.count);
}
};
class NewCounter :public Counter // писать здесь protected Counter и все равно не помогло
{
public:
NewCounter(int c): Counter(c)
{}
Counter operator -(Counter t2)
{
return (this->count + t2.count);
//ошибка в t2.count, пишет: "не удается получить доступ к защищенному члену Counter::count"
}
};
int main()
{
Counter t1(5), t2(4), t3;
t3 = t1 + t2;
t3.get_count();
_getch();
return 0;
}

NewCounter 中奇怪的减法运算符出于某种原因实现了加法。
实际上是问题的答案。在其方法之外无法访问 Counter 类型的 count 成员,因为该成员是受保护的。这样做:
UPD1:
我想了一点关于如何在没有朋友的情况下为 NewCounter 和 Counter 制作加法运算符并获得访问函数,但只能在初始化构造函数的帮助下。这就是发生的事情:
此处的格式略有更改,因此示例占用的行数更少。算子都是加法算子。在加法运算符中,引入了所需类型的显式返回值。并引入了初始化构造函数。在http://cpp.sh/和https://gcc.godbolt.org/ x86-64 转换器 gcc 7.2 上测试。