如何将此对象传递给另一个对象并使用友元类 (c++) 访问其变量

How do I pass this object to another Object and access its variables using a friend class (c++)

本文关键字:友元 c++ 变量 访问 对象 一个对象      更新时间:2023-10-16

所以我搜索了高低,也许我不知道我想问什么问题,如果是这种情况,请帮助我弄清楚那可能是什么。

我正在尝试从汽车类中打印出myCar对象的颜色,使用来自man类的myMan对象的函数。我(认为)我将男人类作为汽车类的朋友,所以我不知道为什么我无法访问汽车私人颜色变量。有人可以告诉我为什么我无法访问汽车私人颜色变量吗?我必须使用朋友。

我已经尝试这样做了

20 多个小时,我已经到了智慧的尽头。我已经包含了我拥有的所有文件,因为我看到它以其他方式完成(全部在一个文件中),并且似乎无法像这样重现它。

错误

1 错误 C2433: "man": 数据声明中不允许使用"朋友" car.h 第 14 行

错误

2 错误 C4430:缺少类型说明符 - 假定为 int。注意:C++不支持默认的 car.h 第 14 行

错误

3 错误 C2248:"car::color":无法访问在类"car"中声明的私人成员 人.cpp第 13 行

错误

4 错误 C2061:语法错误:标识符"汽车"man.h 第 16 行

错误

5 错误 C2660:"man::p rintCarColor":函数不接受 1 个参数 来源.cpp第 16 行

错误

6 错误 C2061:语法错误:标识符"汽车"man.h 第 16 行

车.H

#pragma once
#include <iostream>
#include <string>
#include "man.h"
using namespace std;
class car
{
public:
    car();
    car(string);
    ~car();
    friend man;
private:
    string color;
};

车.cpp

#include "car.h"

car::car()
{
}
car::car(string c){
    color = c;
}
car::~car()
{
}

曼·

#pragma once
#include <iostream>
#include <string>
#include "car.h"
using namespace std;

class man
{
public:
    string name;
    man();
    man(string);
    void printCarColor(car);
    ~man();
};

男人.cpp

#include "man.h"

man::man()
{
}
man::man(string newname)
{
    name = newname;
}
void man::printCarColor(car mycar){
    cout << mycar.color;
}
man::~man()
{
}

来源.cpp

#include <iostream>
#include <string>
#include "car.h"
#include "man.h"
using namespace std;
int main()
{
    car myCar("green");
    //cout << myCar.color;
    man myMan("Jim");
    myMan.name;
    myMan.printCarColor(myCar);
    system("pause");
    return 0;
}

你有一个循环包含依赖项。 car.h 包括 man.h,man.h 包括 car.h。这是行不通的。从car.h中删除 #include"man.h",使用朋友类man而不是朋友man。

**希望这不是回答这个问题的坏方法,功劳归^