我是一名试图学习C++的JAVA开发人员,但我真的不知道标准函数声明的最佳实践是什么.
在课堂里:
class Clazz
{
public:
void Fun1()
{
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
或者在外面:
class Clazz
{
public:
void Fun1();
}
Clazz::Fun1(){
// Do something
}
Run Code Online (Sandbox Code Playgroud)
我觉得第二个可读性较差......
650*_*502 49
C++是面向对象的,因为它支持面向对象的软件开发范例.
但是,与Java不同,C++并不强制您在类中对函数定义进行分组:声明函数的标准C++方法是仅声明一个函数,而不使用任何类.
如果您正在讨论方法声明/定义,那么标准方法是将声明仅放入包含文件(通常命名为).h或.hpp定义在单独的实现文件(通常命名为.cpp或.cxx)中.我同意这确实有些烦人,需要一些重复,但这就是语言的设计方式.
对于快速实验和单个文件项目,任何事情都可行......但对于更大的项目,这种分离是实际需要的.
注意:即使您了解Java,C++也是一种完全不同的语言......而且它是一种无法通过实验学习的语言.原因是它是一种相当复杂的语言,有很多不对称和明显不合逻辑的选择,最重要的是,当你犯了一个错误时,没有"运行时错误天使"可以像Java一样拯救你......但是有"未定义的行为守护进程".
学习C++的唯一合理方法是阅读...无论你多聪明,你都无法猜出委员会的决定(实际上聪明有时甚至是一个问题,因为正确答案是不合逻辑的,是历史的结果遗产.)
只需挑选一本好书,然后阅读封面即可.
Aji*_*aze 15
函数定义在课外更好.这样,如果需要,您的代码可以保持安全.头文件应该只提供声明.
假设有人想要使用你的代码,你可以给他.h文件和你的类的.obj文件(编译后获得).他不需要.cpp文件来使用您的代码.
这样,任何人都无法看到您的实施.
小智 9
"Inside the class"(I)方法与"class of class"(O)方法的作用相同.
但是,当一个类仅用于一个文件(在.cpp文件中)时,可以使用(I).(O)在头文件中使用.cpp文件总是被编译.使用#include"header.h"时会编译头文件.
如果在头文件中使用(I),则每次包含#include"header.h"时都会声明函数(Fun1).这可能导致多次声明相同的功能.这很难编译,甚至可能导致错误.
正确使用示例:
File1:"Clazz.h"
//This file sets up the class with a prototype body.
class Clazz
{
public:
void Fun1();//This is a Fun1 Prototype.
};
Run Code Online (Sandbox Code Playgroud)
File2:"Clazz.cpp"
#include "Clazz.h"
//this file gives Fun1() (prototyped in the header) a body once.
void Clazz::Fun1()
{
//Do stuff...
}
Run Code Online (Sandbox Code Playgroud)
File3:"UseClazz.cpp"
#include "Clazz.h"
//This file uses Fun1() but does not care where Fun1 was given a body.
class MyClazz;
MyClazz.Fun1();//This does Fun1, as prototyped in the header.
Run Code Online (Sandbox Code Playgroud)
File4:"AlsoUseClazz.cpp"
#include "Clazz.h"
//This file uses Fun1() but does not care where Fun1 was given a body.
class MyClazz2;
MyClazz2.Fun1();//This does Fun1, as prototyped in the header.
Run Code Online (Sandbox Code Playgroud)
File5:"DoNotUseClazzHeader.cpp"
//here we do not include Clazz.h. So this is another scope.
class Clazz
{
public:
void Fun1()
{
//Do something else...
}
};
class MyClazz; //this is a totally different thing.
MyClazz.Fun1(); //this does something else.
Run Code Online (Sandbox Code Playgroud)