所以我被要求为大学类(class)创建一个函数的 friend ,我对实现有点迷茫。问题指出“添加一个函数 showCat(Cat&) 作为 Cat 的 friend 。
此函数应该以与 相同的方式显示猫的详细信息。猫::showCat() 功能做"
程序如下
#include<iostream>
#include<string>
using namespace std;
class Cat
{
private:
string name;
string breed;
int age;
static constexpr double licenseFee = 10;
public:
void setCatData(string, string, int);
void showCat();
friend void showCat(const Cat& cat); //friend function declaration
};
void Cat::setCatData(string catName, string catBreed, int catAge)
{
name = catName;
breed = catBreed;
age = catAge;
}
void Cat::showCat(const Cat& aCat) //friend function definition
{
cout << "Cat: " << aCat.name << " is a " << aCat.breed << endl;
cout << "The cat's age is " << aCat.age << endl;
cout << "License fee: $" << aCat.licenseFee << endl;
}
void Cat::showCat()
{
cout << "Cat: " << name << " is a " << breed << endl;
cout << "The cat's age is " << age << endl;
cout << "License fee: $" << licenseFee << endl;
}
int main()
{
Cat myCat;
myCat.setCatData("Tigger", "Fluffy unit", 3);
myCat.showCat();
}
提供的注释并不引人注目,但这是我根据提供给我的信息所做的尝试。在声明 friend void showCat(const Cat& cat);
中可以看到我对 friend 功能的尝试在 cat 类的公共(public)成员中。定义可以看成void Cat::showCat(const Cat& aCat)
{
cout << "Cat: " << aCat.name << " is a " << aCat.breed << endl;
cout << "The cat's age is " << aCat.age << endl;
cout << "License fee: $" << aCat.licenseFee << endl;
}
这就是我的错误的根源。在线void Cat::showCat(const Cat& aCat)
我明白了declaration is incompatible with "void Cat::showCat()" (declared at line 34)
我对 friend 的操作方式有点迷茫,所以任何帮助修复我的功能/程序将不胜感激:)
最佳答案
宣言
friend void showCat(const Cat& cat);
声明 showCat(const Cat&)
作为非成员函数。所以你需要这样定义它:
// Note that this is not a member function
void showCat(const Cat& aCat)
{
...
}
关于C++创建一个函数的 friend ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63901287/