在func1
和func2
中是否合法?类方法包含相同的类对象。
例子:
class Foo
{
public:
void func1() {
//...
Foo foo; // Is it legal?
//...
}
// Is it legal in paramete?
void func2(Foo object) {
//...
}
// It is legal using reference
// http://stackoverflow.com/questions/6921185/why-do-objects-of-the-same-class-have-access-to-each-others-private-data
void func3(Foo& object) {
//
}
};
最佳答案
Is it legal?
是的
Why?
class Foo
{
public:
void func1() {
//...
Foo foo; // Is it legal?
//...
}
};
类成员函数的主体是在考虑了整个类定义之后编译的。
因此,整个类都可用于方法的实现,包括方法和在当前方法之后声明的成员。
这在[class.mem]中有介绍
Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors, exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes).
关于c++ - 类方法包含相同的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44044522/