我正在运行一些示例程序来重新熟悉C++,我遇到了以下问题.首先,这是示例代码:
void print_string(const char * the_string)
{
cout << the_string << endl;
}
int main () {
print_string("What's up?");
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,print_string的参数可能已经改为const char * const the_string.哪个更合适呢?
我理解不同之处在于,一个是指向常量字符的指针,而另一个是指向常量字符的常量指针.但为什么这两个都有效呢?什么时候相关?
可能重复:
具有const参数和重载的函数
我对overloading和const声明规则感到困惑.这有两件事让我感到困惑,也许你可以帮助我找到更深层次的误解,导致他们对我感到困惑.;)
首要问题:
我的编译器允许这样:
void f(int & x) {
std::cout << "plain f" << std::endl;
}
void f(const int & x) {
std::cout << "const f" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但是以下导致编译错误(函数已经有一个主体):
void f(int x) {
std::cout << "plain f" << std::endl;
}
void f(const int x) {
std::cout << "const f" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
我认为这是有道理的,因为我认为const只是告诉编译器传递的对象没有改变,在第二种情况下它仍然被复制.但如果这是正确的,为什么我可以使用const重载函数?
换句话说,为什么我使用编译版本并调用这样的函数:
int x1 = 5;
const int x2 = 5;
f(x1);
f(x2);
Run Code Online (Sandbox Code Playgroud)
我得到"普通f"和"const f"而不是"const f"两次?显然现在我也使用const来告诉编译器调用哪个函数不仅仅是引用没有改变.这变得更加混乱,因为如果我删除"普通"版本它工作得很好并且两次调用"const"版本.
现在我的实际问题是什么?我想知道这种行为背后的想法是什么,因为否则记住它是非常困难的.
今天我发现可以在带有一个签名的头文件中声明一个函数,并在具有不同(相似)签名的源文件中实现它.例如,像这样:
// 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)