如何将此对象传递给另一个对象并使用友元类 (c++) 访问其变量
How do I pass this object to another Object and access its variables using a friend class (c++)
所以我搜索了高低,也许我不知道我想问什么问题,如果是这种情况,请帮助我弄清楚那可能是什么。
我正在尝试从汽车类中打印出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。
**希望这不是回答这个问题的坏方法,功劳归^
相关文章:
- C++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 友元函数无法访问私有数据成员 (c++)
- 继承和友元函数,从基类访问受保护的成员
- 将子类方法声明为基类的友元
- 如何在友元函数中使用静态成员而不添加前缀 [类名]::
- 在将函数声明为友元时,尖括号的含义是什么?
- 在模板类之外定义友元函数的正确方法是什么?
- 2个模板化类的非模板友元函数未定义引用错误
- 友元方法作为常量
- C++ 友元函数和私有构造函数
- 使第二个类的构造函数成为第一个类中的友元函数
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 未定义的类模板不会实例化以检查友元函数
- C++类中的友元函数有问题?
- 使用typedef'ed返回类型声明友元函数时出现编译器错误