今天我发现可以在带有一个签名的头文件中声明一个函数,并在具有不同(相似)签名的源文件中实现它.例如,像这样:
// 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)?
编辑 我正在编写迂腐和最大可能的警告级别,我仍然没有收到警告或错误.
尝试了stackeroverflow qn所以它让我思考为什么不重载该函数,我想出了一个稍微不同的代码,但它说该函数不能重载.我的问题是为什么?还是有另一种方式?
#include <iostream>
using std::cout;
class Test {
public:
Test(){ }
int foo (const int) const;
int foo (int );
};
int main ()
{
Test obj;
Test const obj1;
int variable=0;
do{
obj.foo(3); // Call the const function
obj.foo(variable); // Want to make it call the non const function
variable++;
usleep (2000000);
}while(1);
}
int Test::foo(int a)
{
cout<<"NON CONST"<<std::endl;
a++;
return a;
}
int Test::foo (const int a) const
{
cout<<"CONST"<<std::endl;
return a;
}
Run Code Online (Sandbox Code Playgroud) 我正在读这个:const char*const与const char*?
在string.h,strlen定义为:
size_t strlen ( const char * str );
Run Code Online (Sandbox Code Playgroud)
如果我理解正确,strlen需要一个指向const的char的指针.不应该是:
size_t strlen ( const char* const str );
Run Code Online (Sandbox Code Playgroud)
这样可以确保strlen不能修改指针指向不同的指针吗?
或者,是这样的情况:
由于str指针将通过值传递给strlen,因此函数中对此指针的任何更改都不会更改源指针,因此它没关系..
??