C++ 中的 const 过程,Visual Studio C++ 中出现奇怪的错误2010年?
class a{
public:
int b;
static int c;
virtual void mod() const
{
c=4;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
a bi;
return 0;
}
看看这个...使用 Visual Studio C++ 2010 编译器编译它后,我得到...
cpplearningconsole.obj:错误 LNK2001:无法解析的外部符号 “公共:静态int a :: c”(?c@a@@2HA)
我猜这是一个编译器错误。 对我来说,真正的问题是。如果 c 变量是 const,mod 应该能够修改它吗?
谢谢。
class a{
public:
int b;
static int c;
virtual void mod() const
{
c=4;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
a bi;
return 0;
}
Look at this ... After compiling it using Visual Studio C++ 2010 compiler, I get...
cpplearningconsole.obj : error
LNK2001: unresolved external symbol
"public: static int a::c" (?c@a@@2HA)
I guess this is a compiler bug.
For me, the real question is. Should mod be able to modify c variable if it is const?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您刚刚在类定义中声明了静态变量,您需要通过执行
int a::c = 0;
来定义它。You have just declared the static variable in the class definition, you need to define it in the by doing
int a::c = 0;
.这:
不是编译器消息,而是链接器消息。您明白了,因为虽然您已经声明了成员
c
,但尚未定义它。静态成员只需在一个源文件中定义,即可创建它们。就像:对于你的第二个问题,将函数声明为 const 表明它不会修改正在调用的对象。
mod
函数不会修改对象,它会修改静态成员。这就是为什么您没有收到编译器错误的原因。This:
Isn't a compiler message, it's a linker message. You're getting it, because although you have declared the member
c
, you haven't defined it. Static members need to be defined in only one source file, in order for them to be created. Something like:As for your second question, declaring a function as
const
, states that it doesn't modify the object that it's being called on. Youmod
function doesn't modify the object, it modifies the static member. Which is why you don't get a compiler error.您应该为变量成员添加正确的定义,在类中只有声明。在您的 cpp 中或在类声明之后(在其外部)添加:
int a::c = 0;
You should add the correct definition for your variable member, in the class you only have the declaration. In your cpp or just after the class declaration (outside of it) add:
int a::c = 0;
回答您的其他问题:
c
是您的类的公共静态成员。 任何人都可以改变它的值,那为什么不可以mod()
呢?To answer your other question:
c
is a public static member of your class. Anyone can change its value, so why notmod()
?