Skip to content

Instantly share code, notes, and snippets.

@pezy
Created June 12, 2014 06:48
Show Gist options
  • Save pezy/9ecd15a4ab7a543f02bc to your computer and use it in GitHub Desktop.
Save pezy/9ecd15a4ab7a543f02bc to your computer and use it in GitHub Desktop.
脑子犯二,今天被同事耻笑了。
#include <iostream>
class Father
{
public:
Father():i_(2){}
~Father(){}
int GetIValue(){return i_;}
void SetIValue(int i){i_ = i;}
protected:
int i_;
};
class Son : public Father
{
public:
Son():Father(){}
~Son(){}
};
int main()
{
Father *father = new Father;
std::cout << "Father:" << father->GetIValue() << std::endl;
Son *son = new Son;
std::cout << "Son:" << son->GetIValue() << std::endl;
// change father's value
father->SetIValue(5);
std::cout << "Father(changed):" << father->GetIValue() << std::endl;
std::cout << "Son(changed):" << son->GetIValue() << std::endl;
return 0;
}

###解释一下吧

今天突发奇想(有时候突发奇想会害死人),C++中通过子类对象能否拿到父类对象中的成员呢?我想基本的继承是允许这么干的吧。但凡是应该写程序试一试才知道,于是就写了上面那个程序。

(犯二的开始:)通过输出结果可知,是拿不到的。莫非子类对象有自己独立的内存地址?想的越来越远。

结果请同事来释疑,同事定睛一看,擦,你这是啥呀,分明是两个对象,有何意义?

额,有何意义!!!

他还让我在看看《C++ Primer》,我顿时感觉我学C++都学狗屁了。。。

@Mooophy
Copy link

Mooophy commented Aug 29, 2014

Please...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment