我的班级/指针有问题。
我有两个课程FirstClass
和SecondClass
。
FirstClass
有两个指点:
MyClass *character1;
MyClass *character2;
我稍后在我的代码中分配给这些指针,但现在我有SecondClass
我还有2个指针:
MyClass *oldChar1;
MyClass *oldChar2;
我想将oldChar
设置为与character
所指示的相同。我在SecondClass
中使用friend子句在FirstClass
中创建了一个函数。
void SecondClass::setChars()
{
*oldChar1 = FirstClass::character1;
*oldChar2 = FirstClass::character2;
}
结果:
illegal reference to non-static member 'FirstClass::character1'
我不明白:/有人可以帮助我吗?
答案 0 :(得分:0)
有几种方法可以做到这一点。
在两个班级(source)中共享的朋友功能。
友元函数可以访问类MyFirstClass和MySecondClass的数据成员,但仍然需要告诉友元函数使用哪些类的实例(参见this),例如
class MyClass {
};
class MySecondClass; //forward declaration for later
class MyFirstClass {
private:
MyClass *character1;
MyClass *character2;
public:
//friend function
friend void setChars(MyFirstClass& c1, MySecondClass& c2); //<---- friend function
};
class MySecondClass {
private:
MyClass *oldChar1;
MyClass *oldChar2;
public:
//friend function
friend void setChars(MyFirstClass& c1, MySecondClass& c2);
};
//define the friend function
void setChars(MyFirstClass& c1, MySecondClass& c2) {
c2.oldChar1 = c1.character1;
c2.oldChar2 = c1.character2;
}
int main() {
MyFirstClass c1;
MySecondClass c2;
setChars(c1,c2);
}
朋友类。 使MySecondClass成为MyFirstClass的朋友。 MySecondClass将有方法setChars,它将MyFirstClass的一个实例作为参数。 e.g。
class MyClass {
};
class MySecondClass;
class MyFirstClass {
private:
MyClass *character1;
MyClass *character2;
public:
friend MySecondClass; //<----- friend class
};
class MySecondClass {
private:
MyClass *oldChar1;
MyClass *oldChar2;
public:
void setCharsUsingFriendClass(MyFirstClass& c1) {
oldChar1 = c1.character1;
oldChar2 = c1.character2;
}
};
int main() {
MyFirstClass c1;
MySecondClass c2;
c2.setCharsUsingFriendClass(c1);
}
最后使用2个getter方法。我认为这种方法更好,因为它允许类隐藏它们的实现细节(encapsulation)。
class MyClass {
};
class MySecondClass;
class MyFirstClass {
private:
MyClass *character1;
MyClass *character2;
public:
//define getters to access the private members
MyClass* GetCharacter1() {return character1;}
MyClass* GetCharacter2() {return character2;}
};
class MySecondClass {
private:
MyClass *oldChar1;
MyClass *oldChar2;
public:
void setCharsUsingGetters(MyFirstClass& c1) {
oldChar1 = c1.GetCharacter1();
oldChar2 = c1.GetCharacter2();
}
};
int main() {
MyFirstClass c1;
MySecondClass c2;
c2.setCharsUsingGetters(c1);
}