[英]"static_cast" with pointers and objects in C++
我剛剛了解了 inheritance 並開始使用鑄造。 當我試圖了解這個話題時,我發現自己面臨着這個我無法解釋的問題。 這是代碼:
#include <iostream>
#include <string>
using namespace std;
__interface AbstractClass {
void Eat()const;
void Sleep()const;
void Work()const;
string Info();
};
class Employee : public AbstractClass {
private:
string lastName;
int age, salary;
static int EmpCounter;
protected:
string name;
public:
Employee(string n = "Avto", string ln = "Chachandize", int a = 18, int s = 3000)
: name(n), lastName(ln), age(a), salary(s) {
EmpCounter++;
}
virtual ~Employee() {
EmpCounter--;
}
static int getEmpCounter() {
return EmpCounter;
}
void Eat()const override {
cout << name << " Is eating" << endl;
}
void Sleep()const override {
cout << name << " Is sleeping" << endl;
}
void Work()const override {
cout << name << " Is doing his/her stuff" << endl;
}
string Info() override {
string a = to_string(age);
string s = to_string(salary);
return name + ' ' + lastName + ' ' + a + ' ' + s + ' ';
}
};
int Employee::EmpCounter = 0;
class Developer : public Employee {
string language;
public:
Developer(string n = "Avto", string ln = "Chachandize", int a = 18, int s = 3000, string l = "C++") :
Employee(n, ln, a, s), language(l) {}
~Developer()override = default;
void Work()const override {
cout << name << " Is writing code in " << language << endl;
}
string Info() override {
Employee* emp = static_cast<Employee*>(this);
//Employee emp = static_cast<Employee>(*this);
return emp->Info() + ' ' + language;
}
};
int main() {
Developer dev;
cout << dev.Info() << endl;
}
我試圖將Developer
向上轉換為Employee
,然后獲取他的信息。 但是使用指針轉換的 static 給了我錯誤。
奇怪的是,被評論的第二個沒有。 我不知道這是什么原因。 我也參考了它,也有錯誤。 使用動態轉換時發生了同樣的事情。
string Info() override {
Employee* emp = static_cast<Employee*>(this);
//Employee emp = static_cast<Employee>(*this);
return emp->Info() + ' ' + language;
}
所以我的問題是,這是否應該是一個錯誤?
正如建議的那樣,當您想要從指向 ZA8CFDE6331BD59EB2AC96F8911C4B6666Z 到子 ZA8CFDE6331BD59EB2AC96F8911C4B6666Z 的指針獲取指向 object 的指針到基礎 class 的指針時,您不需要使用強制轉換。 但是您似乎想在子 class(“開發人員”)的“Info”方法的主體內調用基礎 class(“Employee”)的“Info”方法。 可以通過以下方式完成:
Employee::Info();
例如在你的情況下:
string Info() override {
return Employee::Info() + ' ' + language;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.