gpt4 book ai didi

c++ - 函数重载时对调用起决定作用的是什么?

转载 作者:行者123 更新时间:2023-11-30 00:39:05 25 4
gpt4 key购买 nike

我只是想知道什么是在期间进行函数调用的决定性因素重载。据我所知,它是参数的签名,传递的参数数量其中起着重要作用。但是 const 部分是否也起着重要的作用是否参与重载。重载第一个和第二个函数工作正常但如果添加第三个函数以 const 作为传递参数的特征,我得到编译错误。 int A::sum(int, int) 和 int A::sum(int, int) 不能重载。只给出类的代码片段:

class A
{
private:
int x;
int y;

public:
int sum ( int a, int b )
{
cout << " Inside 1st ";
return (a+b) ;
}

int sum (int a ,int b) const
{
cout << " Inside 2nd ";
return (a+b) ;
}

int sum (const int a ,const int b)
{
cout << " Inside 3rd ";
return (a+b) ;
}

A(){x=0;y=0;}
~A(){};
};

当我声明普通对象并调用 sum 时,第一个函数被调用,如果是 const 对象,第二个 sum 被调用。那很好。但是,如果我同时编写第一个和第三个函数,它就会成为一个问题。为什么会这样?

最佳答案

您可以重载 const-ness,但仅​​限于它实际产生影响的地方。我的意思是“实际上有所作为”?好吧,如果你声明

void foo(char *ptr);
void foo(const char *ptr);

const 很重要:您是说 foo 的一个重载保证不会修改 ptr 指向,而另一个则没有。但是如果你声明

void foo(int x);
void foo(const int x);

const 没关系:标量参数总是按值传递,因此 foo 的假设变体都不能修改x 在它的调用者中,即使它想要。因此,C++ 标准说 const 被丢弃,这是相同函数的两种不同声明,其中一种是错误的。

const 相对于 * 的位置很重要。指针本身就是一个标量,因此它们也是同一函数的两个声明:

void foo(char *ptr);
void foo(char *const ptr);

因为这里 const 限定了指针本身而不是它指向的对象。

这将我们带到了方法:方法声明的参数列表之后的 const 限定符应用于 this 指向的对象,并且可以重载:

struct A
{
int foo (char *ptr);
int foo (char *ptr) const;
int foo (const char *ptr);
int foo (const char *ptr) const;
};

您应该将这些声明视为在内部重写为:

struct A {};
int A_foo (A *this, char *ptr);
int A_foo (const A *this, char *ptr);
int A_foo (A *this, const char *ptr);
int A_foo (const A *this, const char *ptr);

然后一切都按照重载函数的正常规则运行。

关于c++ - 函数重载时对调用起决定作用的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9343803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com