這個想法是:
我有 2 個類,一個
printName,另一個Human用 variable命名name。我想printName列印類name中的任何變數Human。
例子:
class Print {
public:
char name[255]; // name will be overridden from Human class.
void print() { std::cout << name << std::endl; } // `this.name` should be from Human class.
};
class Human : public Print {
public:
char name[255];
};
int main() {
Human h;
h.name = "Somename";
h.print(); // Should outputs: Somename
}
uj5u.com熱心網友回復:
解決方案之一:奇怪重復的模板模式1、2。
template <typename T>
class Print {
public:
char name[255];
void print() { std::cout << static_cast<T*>(this)->name << std::endl; }
};
class Human : public Print<Human> {
public:
char name[255];
};
int main() {
Human h;
h.name = "Somename";
h.print(); // Outputs: Somename
}
h.name = "Somename"不會編譯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/496385.html
上一篇:如何在另一個類方法中參考類屬性?
