关于重载的赋值运算符的继承

pkueecs13 2014-03-24 11:42:32
为什么有时候能被继承,有时候不能呢?
看下面这两个程序:
第一个:
#include<iostream>
using namespace std;
class base
{
private:
int i;
public:
base(){}
void operator=(base& n)
{
cout<<"base::operator=() called"<<endl;
}
};
class derived:public base
{
private:
int j;
public:
derived(){}
};
int main()
{
base a;
derived b,c;
b=c;
}
输出结果是 base::operator=() called

第二个:
#include<string.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
class A1
{
public:
int operator=(int a)
{
return 8;
}

int operator+(int a)
{
return 9;
}
};

class B1 : public A1
{
public:
int operator-(int a)
{
return 7;
}
};

int main()
{
A1 x;
cout<<(x=2)<<endl;
B1 v,u;
v=u;
cout << (v + 2) << endl; // OK, print 9
cout << (v - 2) << endl; // OK, print 7
cout << (v = 2) << endl; // Error, see below

return 0;
}
在最后一个cout会报错,编译不过,提示error: no match for 'operator=' in 'v = 2'
...全文
51 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
PDD123 2014-03-25
  • 打赏
  • 举报
回复
我看着怎么应该是在 v=u; 这句上出错?
pkueecs13 2014-03-24
  • 打赏
  • 举报
回复
[code=c#include<iostream> using namespace std; class base { private: int i; public: base(){} void operator=(base& n) { cout<<"base::operator=() called"<<endl; } }; class derived:public base { private: int j; public: derived(){} }; int main() { base a; derived b,c; b=c; } ][/code]
pkueecs13 2014-03-24
  • 打赏
  • 举报
回复
[code=c#include<iostream> using namespace std; class base { private: int i; public: base(){} void operator=(base& n) { cout<<"base::operator=() called"<<endl; } }; class derived:public base { private: int j; public: derived(){} }; int main() { base a; derived b,c; b=c; } ][/code]
#include<string.h>
#include<stdlib.h>
#include<string>
#include<iostream>
using namespace std;
class A1
{
public:
        int operator=(int a)
        {
                return 8;
        }

        int operator+(int a)
        {
                return 9;
        }
};

class B1 : public A1
{
public:
        int operator-(int a)
        {
                return 7;
        }
};

int main()
{
        A1 x;
        cout<<(x=2)<<endl;
        B1 v,u;
        v=u;
        cout << (v + 2) << endl; // OK, print 9
        cout << (v - 2) << endl; // OK, print 7
        cout << (v = 2) << endl; // Error, see below

        return 0;
}
代码重发了下,看得清楚

65,209

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧