问题描述
我有一个在类Foo中定义的成员static const int x,我通过引用传递
,并在其他地方传递值(参见下面的代码)。传递它
的价值是有效的,但是参考它并不是:它认为x是未定义的。
有人可以解释这里发生了什么吗?为什么我不能通过引用传递一个静态的
const成员?
这就是我编译它的方式:
g ++ -g -Wall sample_main.C#g ++ -v 4.0.1
/tmp/ccUJx59K.o(.gnu.linkonce.t._ZN3Foo12bad_functionER 3Bar [Foo :: bad_function(Bar& )] + 0xa):在函数`Foo :: bad_function(Bar&)'':
/tmp/STATICCONST/sample_main.C:18:未定义引用`Foo :: x''
collect2:ld返回1退出状态
#include< cstdlib>
使用命名空间std;
class Bar
{
public:
void good(const int a){}
void bad (const int& a){}
};
class Foo
{
public:
static const int x = 0;
void good_function(class Bar& B){B.good(x); }
无效bad_function(类Bar& B){B.bad(x); }
};
int main(int argc,char * argv [])
{
Foo F;
Bar B;
F.good_function(B);
F.bad_function(B);
返回0;
}
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?
This is how I compile it:
g++ -g -Wall sample_main.C # g++ -v 4.0.1
/tmp/ccUJx59K.o(.gnu.linkonce.t._ZN3Foo12bad_functionER 3Bar[Foo::bad_function(Bar&)]+0xa): In function `Foo::bad_function(Bar&)'':
/tmp/STATICCONST/sample_main.C:18: undefined reference to `Foo::x''
collect2: ld returned 1 exit status
#include <cstdlib>
using namespace std;
class Bar
{
public:
void good(const int a) {}
void bad(const int & a) {}
};
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); }
};
int main(int argc, char * argv[])
{
Foo F;
Bar B;
F.good_function(B);
F.bad_function(B);
return 0;
}
推荐答案
添加:
const int Foo :: x;
Add this:
const int Foo::x;
你可以但不同的是,当你通过值传递编译器时/>
替换值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
你可以但不同的是,当你通过值传递时,编译器会替换为值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
这篇关于通过引用传递静态const int成员的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!