What is the proper signature of the main function in C++? What is the correct return type, and what does it mean to return a value from main? What are the allowed parameter types, and what are their meanings?
这是系统特定的吗?这些规则会随着时间而改变吗?如果我违反它们会发生什么?
我最近遇到了这个语法try-catchfor function.
struct A
{
int a;
A (int i) : a(i) // normal syntax
{
try {}
catch(...) {}
}
A () // something different
try : a(0) {}
catch(...) {}
void foo () // normal function
try {}
catch(...) {}
};
Run Code Online (Sandbox Code Playgroud)
两种语法都有效.除了编码风格之外,这些语法之间是否有任何技术差异?在任何方面,语法之一是否优于其他语法?
我正在编写一本关于C++的书和关于它有错误的章节(我留下了一些小问题,但主要是这个):
int main()
try {
// our program (<- this comment is literally from the book)
return 0;
}
catch(exception& e) {
cerr << "error: " << e.what() << '\n';
return 1;
}
catch(...) {
cerr << "Unknown exception\n";
return 2;
}
Run Code Online (Sandbox Code Playgroud)
这编译但当然没有做任何事情,所以我仍然在想
关于函数有一个try-catch的东西,我认为有时可能非常有用:
bool function()
try
{
//do something
}
catch(exception_type & t)
{
//do something
}
Run Code Online (Sandbox Code Playgroud)
所以问题的第一部分:这种风格在一般情况下是否被认为是不好的?
我使用这种方法的具体例子:
我们在c和c ++中有很多代码的项目.我们有自定义异常类型(不是std :: exception派生的).我需要集成XML库并将所有异常强制转换为我们的类型.所以,基本上,最后一步是从XML库中捕获所有异常并转换它们.
功能之前:
bool readEntity(...)
{
while(...)
{
if(...)
{
//lot's of code...
}
}
}
Run Code Online (Sandbox Code Playgroud)
后:
bool readEntity(...)
try
{
while(...)
{
if(...)
{
//lot's of code...
}
}
}
catch(XMLBaseException & ex)
{
//create our exception and throw
}
Run Code Online (Sandbox Code Playgroud)
我的想法是这样的:我明确表示我的意图将从一种类型派生的所有异常转换为自定义类型并且我们保持我们的屏幕没有水平滚动条(因为水平滚动条是坏的).
好吧,在代码审查期间,我对这种方法的批评非常明确.
所以我想听听你的想法.
更新:要明确:重构函数不是一个选项.实际上它写得很好.
今天我发现可以在带有一个签名的头文件中声明一个函数,并在具有不同(相似)签名的源文件中实现它.例如,像这样:
// THE HEADER example.hpp
#ifndef EXAMPLE_HPP
#define EXAMPLE_HPP
int foo( const int v );
#endif
// THE SOURCE FILE example.cpp
#include "example.hpp"
int foo( int v ) // missing const
{
return ++v;
}
Run Code Online (Sandbox Code Playgroud)
这是允许的吗?或者这是编译器的扩展(我使用的是g ++ 4.3.0)?
编辑 我正在编写迂腐和最大可能的警告级别,我仍然没有收到警告或错误.