avatar
c++ 是否也有class method??# Programming - 葵花宝典
G*A
1
即在不不实例化任何对象的情况下,仍然能够用class method 实现一些功能(输出字符
串)?
比如,在Ruby下,可以这样做:
>>class Person
>> def self.info
>> puts "Hi, Ni hao"
>> end
>>end
>>Person.info
输出:
>>Hi, Ni hao
不知道用c++可以不??谢谢回答
avatar
s*e
2
static method.
class person{
public:
static void info() const{ std::cout<};
person::info();

【在 G****A 的大作中提到】
: 即在不不实例化任何对象的情况下,仍然能够用class method 实现一些功能(输出字符
: 串)?
: 比如,在Ruby下,可以这样做:
: >>class Person
: >> def self.info
: >> puts "Hi, Ni hao"
: >> end
: >>end
: >>Person.info
: 输出:

avatar
z*e
3
sure.
don't have to be static. Once the method doesn't use "this", even it's null,
you can still use it.
e.g.
class A
{
public:
void output(){cout<};
...
A* a=null;
a->output();
..
it should work.

【在 G****A 的大作中提到】
: 即在不不实例化任何对象的情况下,仍然能够用class method 实现一些功能(输出字符
: 串)?
: 比如,在Ruby下,可以这样做:
: >>class Person
: >> def self.info
: >> puts "Hi, Ni hao"
: >> end
: >>end
: >>Person.info
: 输出:

avatar
X*r
4
This is bad programming practice. Don't ever do this.

null,

【在 z***e 的大作中提到】
: sure.
: don't have to be static. Once the method doesn't use "this", even it's null,
: you can still use it.
: e.g.
: class A
: {
: public:
: void output(){cout<: };
: ...

avatar
m*t
5

I mean I haven't done C++ for a while, but doesn't this code break any time
when A::output() is changed to either reference an instance member, or
becomes virtual? And what do we gain from doing this, exactly?
This sounds to me very much like pointing a shotgun at your own foot, rig
the trigger with some remote control, and fedex the remote control to
somebody half a globe away, with a note that says "press whenever you like".

【在 z***e 的大作中提到】
: sure.
: don't have to be static. Once the method doesn't use "this", even it's null,
: you can still use it.
: e.g.
: class A
: {
: public:
: void output(){cout<: };
: ...

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。