相关疑难解决方法(0)

What is the proper declaration of main?

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?

这是系统特定的吗?这些规则会随着时间而改变吗?如果我违反它们会发生什么?

c++ program-entry-point c++-faq

144
推荐指数
2
解决办法
9万
查看次数

函数的try-catch语法之间的区别

我最近遇到了这个语法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++ syntax try-catch function-try-block

43
推荐指数
2
解决办法
5595
查看次数

main()周围没有花括号 - 为什么这有效?

我正在编写一本关于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)

这编译但当然没有做任何事情,所以我仍然在想

  1. 为什么在main()之后没有一组花括号括起来?是块还是我称之为"流行语"(ha!)是main()的一部分还是没有?
  2. 如果它们是函数,那么在catch之前没有"int"(无论如何)?
  3. 如果它们不是功能,它们是什么?
  4. 重新捕捉(...),我从未见过用这种方式使用的椭圆.我可以在任何地方使用省略号来表示"任何东西"吗?

c++ syntax error-handling

27
推荐指数
3
解决办法
2106
查看次数

c ++中的函数范围的异常处理 - 这是一种糟糕的风格吗?

关于函数有一个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)

我的想法是这样的:我明确表示我的意图将从一种类型派生的所有异常转换为自定义类型并且我们保持我们的屏幕没有水平滚动条(因为水平滚动条是坏的).

好吧,在代码审查期间,我对这种方法的批评非常明确.

所以我想听听你的想法.

更新:要明确:重构函数不是一个选项.实际上它写得很好.

c++ coding-style exception

6
推荐指数
1
解决办法
1207
查看次数

定义具有不同签名的函数

今天我发现可以在带有一个签名的头文件中声明一个函数,并在具有不同(相似)签名的源文件中实现它.例如,像这样:

// 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)?

编辑 我正在编写迂腐和最大可能的警告级别,我仍然没有收到警告或错误.

c++ language-lawyer

5
推荐指数
2
解决办法
817
查看次数