[英]How to set the value of a variable of derived class by using the base class object?
我需要通過A
對象a
將x = 2000
分配給B
x
B是派生類,即繼承類A。
class A
{
public:
int x, y;
void print()
{
cout<<endl<<"print() of A";
}
virtual void display()
{
cout<<endl<<"display() of A";
}
};
class B: public A
{
public:
int x, z;
void display()
{
cout<<endl<<"display() of B";
}
void print()
{
cout<<endl<<"print() of B";
}
};
通過執行以下操作找到了答案:
((B *)aptr)->x = 2000;
在C ++中,多態是通過虛函數實現的。 如果您需要通過指針或對其基類型的引用來更改派生類中的某些內容,則需要一個虛函數。 (從技術上講,您不是這樣;可以將其轉換為派生類型,但這是對設計失敗的承認)。
這可以通過在基類中創建虛擬函數來完成,該函數將調用派生類的函數進行初始化。
#include<iostream>
#include<stdio.h>
using namespace std;
class A
{
public:
int x, y;
void print()
{
cout<<endl<<"print() of A";
}
virtual void display()
{
cout<<endl<<"display() of A";
}
virtual void setX(int a)
{
}
};
class B: public A
{
public:
int x, z;
void display()
{
cout<<endl<<"display() of B";
}
void print()
{
cout<<endl<<"print() of B";
}
void setX(int a)
{
x=a;
}
};
int main()
{
A *ptr;
B b;
ptr=&b;
ptr->setX(2000); ///using pointer object of class A
cout<<b.x;
}
我認為這會對您有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.