【发布时间】:2014-01-13 09:45:51
【问题描述】:
在 C++ 中,我使用多态类和友谊来创建一个基本的“朋友组”。但是,当我试图访问班级人(班级男孩的朋友)的私人年龄功能时,我无法访问它。有什么问题?
/* Polymorphic Classes and Class Friendship */
#include <iostream>
class Person{
public:
Person(char* name, int age) : Name(name), Age(age){}
char* Name;
virtual void Speak(void){
std::cout << "I am a person called " << Name << std::endl;
}
virtual ~Person(void){delete this;}
private:
int Age;
};
class Boy : public Person{
friend class Person;
public:
Boy(char* name, int age, Person* Friend) : Person(name, age), MyFriend(Friend){}
void Speak(void){
std::cout << "I am a boy called " << Name << ". My friend " << MyFriend->Name << "'s age is " << MyFriend->Age /* Error here */ << std::endl;
}
~Boy(void){delete this;}
private:
Person* MyFriend;
};
int main(void){
Person* John = new Person("John", 12);
Boy* James = new Boy("James", 14, John);
Boy* Keith = new Boy("Keith", 18, James);
John->Speak();
James->Speak();
John->~Person();
James->~Boy();
Keith->~Boy();
return (0);
}
【问题讨论】:
-
您的代码有很多错误,因此唯一明智的建议是让您花一些时间学习 C++ 的基础知识。见this list of C++ books。
标签: c++ class polymorphism friend access-control