C++ T const&;函数返回类型的平均值?
以下函数原型的返回类型是什么C++ T const&;函数返回类型的平均值?,c++,constants,C++,Constants,以下函数原型的返回类型是什么 int const& myfunctionname(int i) 我不能使用const和&here。如果我返回对象/数组/基本上是非局部变量,如果我想返回对象的位置,我应该使用指针还是引用?这样的函数可以返回对它所属类的成员变量的引用,但调用函数将无法更改它。例如: class Foo { public: Foo() {boo=5;} public: int const& myfunctionname(int i) {boo +=
int const& myfunctionname(int i)
我不能使用const和&here。如果我返回对象/数组/基本上是非局部变量,如果我想返回对象的位置,我应该使用指针还是引用?这样的函数可以返回对它所属类的成员变量的引用,但调用函数将无法更改它。例如:
class Foo
{
public:
Foo() {boo=5;}
public:
int const& myfunctionname(int i) {boo += i; return boo;}
private:
int boo;
}
void func(Foo& foo)
{
const int& a = foo.myfunctionname(6);
a += 7; // Compilation error
int b = a+7; // OK
}
const std::string &User()const
{
return m_Username;
}
int Age() const
{
return m_Age; // Pointless to use a reference here
}
const Person *Partner()const
{
return m_Parter; // User may not have a partner, so pointer
}
补充:
通过引用返回常量值的最常见示例可能是
operator++()
它意味着您正在返回一个无法更改的值的引用
如果返回对局部变量的引用,则会出现问题,因为它将引用不再存在的内容:
int const &GetValue()
{
int x = 10;
return x; // THIS IS BAD!
}
另外,返回整型(int、long等)的常量引用也没有什么意义,因为它们占用的空间与最初的引用几乎相同。然而,如果你这样做了,那也没什么大不了的
如果要返回非本地数据(即成员数据),则如果数据始终存在,则使用引用;如果数据可能不存在,则使用指针,这样NULL
表示数据不存在。例如:
class Foo
{
public:
Foo() {boo=5;}
public:
int const& myfunctionname(int i) {boo += i; return boo;}
private:
int boo;
}
void func(Foo& foo)
{
const int& a = foo.myfunctionname(6);
a += 7; // Compilation error
int b = a+7; // OK
}
const std::string &User()const
{
return m_Username;
}
int Age() const
{
return m_Age; // Pointless to use a reference here
}
const Person *Partner()const
{
return m_Parter; // User may not have a partner, so pointer
}
如果您不希望调用方能够修改返回的对象,请将指针或引用设置为const。与:const int&…相同。此函数返回它所属类的成员变量的引用,但调用函数将无法更改它。@barakmanos:So,成员变量本身可以在函数内部修改,但任何调用函数都不能修改它?另外,你能告诉我使用*或-,是否有任何偏好吗?请参阅下面我的答案。。。