C++学习一错误解决_类型未定义
2017-02-10 16:07
393 查看
在C++学习中,使用友元函数时,大多会遇到这样的问题。比如下面的友元全局函数的使用,就存在问题
但是,这就纳闷了。我不是在之前写了class Test;声明了吗?
有这样的感觉是正常的,因为你没理解一个注意。使用类的声明,系统只知道有这样一个声明,并不知道有什么成员。这样在定义和声明之间就只能使用这个类型的引用或者指针
但是在这里的代码中第八行却使用了他的成员。如果把cout << test.m_strName << endl;注释掉,可以正常编译.这就能证明这点。
解决方法有两种:
第一种,把fun全局函数放到后面来。(这种方法适用于友元全局函数)
第二种,是函数的声明写在这里,定义写在需要使用的类的后面。(这种方法,在友元成员函数的定义时是非常有效的,而且某些情况只能使用这种方法,例如下面的代码)
//友元全局函数 #include <iostream> #include <stdlib.h> #include <string> using namespace std; class Test; void fun(Test & test) { cout << test.m_strName << endl; } class Test { friend void fun(Test & test); public: Test(string name):m_strName(name){} private: string m_strName; }; int main(void) { Test a("name"); fun(a); system("pause"); return 0; }这里编译时就会报错:Line 8:Test类型未定义。
但是,这就纳闷了。我不是在之前写了class Test;声明了吗?
有这样的感觉是正常的,因为你没理解一个注意。使用类的声明,系统只知道有这样一个声明,并不知道有什么成员。这样在定义和声明之间就只能使用这个类型的引用或者指针
但是在这里的代码中第八行却使用了他的成员。如果把cout << test.m_strName << endl;注释掉,可以正常编译.这就能证明这点。
解决方法有两种:
第一种,把fun全局函数放到后面来。(这种方法适用于友元全局函数)
第二种,是函数的声明写在这里,定义写在需要使用的类的后面。(这种方法,在友元成员函数的定义时是非常有效的,而且某些情况只能使用这种方法,例如下面的代码)
#include <iostream> #include <stdlib.h> #include <string> using namespace std; class Test2; class Test1 { public: void fun(Test2 & t) { cout << t.m_strName << endl; } }; class Test2 { friend void Test1::fun(Test2 & t); public: Test2(string name): m_strName(name){} private: string m_strName; }; int main() { Test2 t2("name"); Test1 t1; t1.fun(t2); system("pause"); return 0; }
你两个类怎么换都会出错。所以只能使用第二种方法。定义和声明分开。下面就是这样。
#include <iostream> #include <stdlib.h> #include <string> using namespace std; class Test2; class Test1 { public: void fun(Test2 & t); }; class Test2 { friend void Test1::fun(Test2 & t); 4000 public: Test2(string name): m_strName(name){} private: string m_strName; }; void Test1::fun(Test2 & t) { cout << t.m_strName << endl; } int main() { Test2 t2("name"); Test1 t1; t1.fun(t2); system("pause"); return 0; }
相关文章推荐
- C++ 错误error C2011:类型重定义的解决办法
- C++类型重定义错误的解决方法
- 类语句.NET下编译C++代码时出现"error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int"错误的解决方法。
- 错误16error C2011: “Bullet”:“class”类型重定义,如何解决
- error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int 错误的解决方法
- C++模板函数中含有数据类型成员时导致编译错误(显示未知类型)的解决方法
- C++中类定义时不允许使用不完整的类型错误提示原因分析
- C++解决类二次定义错误的方法
- C++学习之重复定义的错误
- SpringMVC + Spring + MyBatis 学习笔记:提交数据遭遇基础类型和日期类型报400错误解决方法
- Duanxx的C++学习: 使用类没有被定义 原因及解决方法
- c++ Premier 学习笔记(unit2 变量和基本类型 -声明与定义
- .NET下编译C++代码时出现"error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int"错误的解决方法。
- C++&nbsp;学习&nbsp;&lt;三&gt;&nbsp;:错误与解决方法
- php学习日志(5)-解决Windows Live Writer错误:WindowsLive.Writer.CoreServices.HttpRequestHelper的类型初始值设定发生异常
- error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int 错误的解决方法
- 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int"错误解决办
- error C4430: 缺少类型说明符 - 假定为 int。注意: C++ 不支持默认 int 错误的解决方法
- C/C++学习笔记25:用typedef定义类型
- C# 001 --- 正确的删除一个控件的事件函数 --- 解决错误: “A”不包含“B”的定义,并且找不到可接受类型为“A”的第一个参数的扩展方法“B”(是否缺少 using 指令或程序集引用?)