class Base
{
private:
int _b;
public:
Base();
Base(int b);
virtual void display();
//Assignment operator overload.
Base& operator=(const Base&);
};
Base::Base()
{
_b = 0;
}
Base::Base(int b)
{
_b = b;
}
void Base::display()
{
cout<<"base value := "<<_b<<endl;
}
Base& Base::operator=(const Base& ob)
{
//Check for self-assignment.
if(this != &ob)
{
this->_b = ob._b;
}
return *this;
}
class Derived : public Base
{
private:
int _d;
public:
Derived();
Derived(int d);
void display();
//Assignment operator overload.
Derived & operator=(const Derived& ob);
};
Derived::Derived() : Base()
{
_d = 0;
}
Derived::Derived(int d) : Base(d)
{
_d = d;
}
void Derived::display()
{
cout<<"Derived value := "<<_d<<endl;
}
Derived & Derived::operator=(const Derived& ob)
{
if(this != &ob)
{
this->_d = ob._d;
}
return *this;
}
int main()
{
Derived d1(10),d2(),d3;
//How d2 becomes lvalue and not d3 above.
d2 = d1;//Error :: expression must be modified lvalue.
//d2.display();
d3 = d1;
return 0;
}
答案 0 :(得分:1)
Derived d2();
被视为函数声明。这样做: -
Derived d1(10),d2,d3;
d2 = d1; /////ahaa it's working
答案 1 :(得分:0)
问题是你的&#39; d2()&#39;。语句d2()不像你想象的那样创建一个名为d2的派生对象。正确的选项是:
Derived d2;
Derived d2 = Derived();
Derived d2(0); // or any other integer
声明
Derived d2();
告诉编译器您正在定义一个不带参数的函数并返回Derived类型。
请点击此处查看更长的解释: error: request for member '..' in '..' which is of non-class type