我试图从 classB 访问 classC 的成员,classC 和 classB 都在 classA 中。这是我正在尝试做的事情;
//hello.h
class hello{
public:
hello();
class letters{
public:
letters();
void setName(char n);
char getName();
private:
char name;
}
class sayHi{
public:
sayHi();
void onJoin();
}
}
//hello.cpp
hello::hello(){}
hello::letters(){}
hello::sayHi(){}
void hello::letters::setName(char n){
hello::letters::name = n; //trying to access the private variable 'name' inside class letters
}
char hello::letters::getName(){
return hello::letters::name = n;
}
void hello::sayHi::onJoin(){
cout<< hello::letters::getName() <<endl;
}
我知道我做错了,我是否应该创建每个类的实例并调用成员?
最佳答案
是的,您应该创建类的实例。
这些通常被称为“对象”,这就是为什么他们称之为“面向对象的编程”。
首先,您的 getName
和 setName
应该如下所示:
void hello::letters::setName(char n) {
name = n;
}
char hello::letters::getName() const { // Declaration should also say "const".
return name;
}
除此之外,任何 sayHi
实例都需要知道要对哪些 letters
说“Hi”,这意味着您需要告诉它。
这通常是通过将参数传递给需要知道的方法来完成的:
class sayHi{
public:
sayHi();
void onJoin(const letters& who)
{
cout << who.getName() << endl;
}
};
你会像这样使用它:
int main()
{
hello::letters letter;
letter.setName('p');
hello::sayHi greeter;
greeter.onJoin(letter);
}
关于c++ - 在一个类中定义两个类,并访问其成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9797705/