且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过引用传递静态const int成员的问题

更新时间:2023-02-05 20:47:58

Amadeus WM写道:

....
Amadeus W. M. wrote:
....

class Foo
{
公开:
static const int x = 0;

void good_function(Class Bar& B){B.good(x); }
void bad_function(类Bar& B){B.bad(x); }
};

class Foo
{
public:
static const int x=0;

void good_function(class Bar & B){ B.good(x); }
void bad_function(class Bar & B) { B.bad(x); }
};




添加:


const int Foo :: x;



Add this:

const int Foo::x;


Amadeus WM写道:
Amadeus W. M. wrote:
我有一个在类Foo中定义的静态const int x成员,我正在通过引用传递它,并且其他地方的价值(见下面的代码)。传递它
按价值工作,但通过引用它不会:它认为x未定义。
有人可以解释这里发生了什么吗?为什么我不能通过引用传递一个静态的
const成员?
I have a member static const int x defined in class Foo, and I''m passing
it by reference, and by value elsewhere (see the code below). Passing it
by value works, but by reference it doesn''t: it thinks x is undefined.
Could someone explain what''s going on here? Why can''t I pass a static
const member by reference?




你可以但不同的是,当你通过值传递编译器时/>
替换值0,因此实际变量的存储空间不需要
。但是当你通过引用传递时,你需要一个实际的变量

你没有声明(类中的内容是定义而不是

声明)。


你需要像Gianni所展示的那样将声明添加到sample_main.C.


john



You can but the difference is that when you pass by value the compiler
substitutes the value 0 so storage for the actual variable is not
needed. But when you pass by reference you need an actual variable which
you have failed to declare (what is in the class is a definition not a
declaration).

You need to add the declaration to sample_main.C as Gianni showed.

john


John Harrison写道:
John Harrison wrote:
Amadeus WM写道:
Amadeus W. M. wrote:
我有一个成员静态const int x在Foo类中定义,我正在传递
它通过引用,并在其他地方的值(见下面的代码)。传递它
按价值工作,但通过引用它不会:它认为x未定义。
有人可以解释这里发生了什么吗?为什么我不能通过引用传递一个静态的
const成员?
I have a member static const int x defined in class Foo, and I''m passing
it by reference, and by value elsewhere (see the code below). Passing it
by value works, but by reference it doesn''t: it thinks x is undefined.
Could someone explain what''s going on here? Why can''t I pass a static
const member by reference?



你可以但不同的是,当你通过值传递时,编译器会替换为值0因此不需要实际变量的存储空间。但是当你通过引用传递时,你需要一个实际的变量,你没有声明(类中的内容是定义而不是
声明)。

你需要如Gianni所示,将声明添加到sample_main.C.

john


You can but the difference is that when you pass by value the compiler
substitutes the value 0 so storage for the actual variable is not
needed. But when you pass by reference you need an actual variable which
you have failed to declare (what is in the class is a definition not a
declaration).

You need to add the declaration to sample_main.C as Gianni showed.

john




对不起,单词定义和声明完全错误了/>
在上面的解释中回合。


john



Sorry, got the words definition and declaration completely the wrong way
round in the above explanation.

john