English 中文(简体)
现任成员
原标题:Const Member function Vs Const Friend Function
  • 时间:2010-06-17 14:09:53
  •  标签:
  • c++

该法典如何更改一项综合职能的价值:

#include<iostream>
using namespace std;
class Y;
class X{
  public:
    void access(Y &y) const;
};

class Y{
    int d;
  public:
    friend void X::access(Y &y) const;
    Y(){d=0;}
}; 

void X::access(Y &y) const 
{
    cout<<"Y is "<<y.d<<endl;
    y.d=1;
    cout<<"Y is "<<y.d<<endl;
}

int main() {
    X x;
    Y y;
    x.access(y);
}

该法典有错误:

#include<iostream>

using namespace std;

class Y{
    int d;
  public:
    void set() const{d=0;}
};                          

int main() {
    Y y1;
    return 0;
}
最佳回答

由于在<代码>const功能之内,只有* > ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ ∗ 系>const,而不是功能参数或其他任何内容。

问题回答

因为,在你的第一个例子中:

void X::access(Y &y) const;

<代码>const 记录员告诉编辑,该功能赢得了对<条码>X的修改,反对隐含的<条码>(<>t>>/code>参数。 <代码>Y,作为参考通过:tt tconst

在第二个例子中,<代码>(>)功能为<代码>Y>/ 代码>的成员:

 void set() const

它宣布,指向Y物体的隐含的<代码>即参数为最线人(因此该物体可作修改)。

如果您希望<代码>X:不允许更改<代码>。 Y 反对通过,将声明改为:

void X::access(Y const& y) const;

首先,在<代码>X:接入(Y &y)和上的组合表示,不能修改<代码>X的标的。 由于<代码>Y参数是用非最基本参考资料计算的,因此可在该职能范围内加以修改。

在第二个例子中,<代码>Y:set() const上的组合表示: Y,其名称不能改动,因此,您不能修改不可变更的成员变量<>d。

a 成员的职能只是承诺不改变其所属类别的任何成员(如果他们被宣布为 mu)。

在第一个例子中,Y.d正在修改方法X:进入。 这种方法并不改变X本身的任何成员,因此完全平静。

然而,在第二个例子中,Y:c()方法被宣布为“灵魂”,因此不能改变Y:d。

页: 1





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签