c++ - 变量等末尾的和号 (&)

标签 c++ reference friend

我是一个 C++ 菜鸟,我在理解代码中的 C++ 语法时遇到了问题。现在我很困惑。

class date
{
private:
int day, month, year;
int correct_date( void );
public:
void set_date( int d, int m, int y );
void actual( void );
void print( void );
void inc( void );
friend int date_ok( const date& );
};

关于“&”字符,我理解它作为引用、地址和逻辑运算符的一般用法......

例如 int *Y = &X

参数末尾的&运算符是什么意思?

friend int date_ok( const date& );

谢谢

编辑:

感谢您的回答。 如果我理解正确的话,变量名就被简单地省略了,因为它只是一个原型(prototype)。对于原型(prototype)我不需要变量名,它是可选的。对吗?

但是,对于函数的定义,我肯定需要变量名,对吧?

最佳答案

const date&被方法date_ok接受表示 date_ok采用 const date 类型的引用.它的工作原理类似于指针,只是语法稍微多一点……甜

在您的示例中,int* Y = &x使Y int * 类型的指针然后分配给它x的地址.当我想更改“Y 指向的地址处的任何内容”的值时,我会说 *Y = 200;

所以,

int x = 300;
int *Y = &x;
*Y = 200; // now x = 200
cout << x; // prints 200

现在我使用引用

int x = 300;
int& Y = x;
Y = 200; // now x = 200
cout << x; // prints 200

关于c++ - 变量等末尾的和号 (&),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20864574/

相关文章:

c++ - 为什么 ReadProcessMemory 有 `lpNumberOfBytesRead` ?

c++ - 调用struct中定义的友元函数需要前向声明?

C++如何避免使用自制的侵入式列表的友元模板函数

c++ - penter 和 pexit 的 Visual Studio 宏

c++ - 如何在c++ 20中将指针变量与consteval一起使用?

c++ - 在 C++ 中,如何在一个参数中测试与 "|"组合的多个标志之一?

javascript - 为什么重新分配后不再反射(reflect)对象的更改?

c# - 程序集绑定(bind)重定向不起作用

c++ - 从 std::string *tab[11] 返回 const std::string*&

c++ - 我应该如何使我的分配器可重新绑定(bind)?我可以在保持其字段私有(private)的同时做到这一点吗?