2015-02-12 62 views
0

我在C++的类和对象中,在那里我很难理解类的减速概念,为此我编写了一个不编译的小程序,任何人都会指导我?如何从C++中的类开始

#include <iostream> 

using namespace std; 

class myClass{ 
    friend increment(myClass, int); 
    private: 
    int topSecret; 
    public: 
    myClass(){ 
     topSecret = 100; 
    } 
    void display(){ 
     cout<<"The value of top Secter is"<<topSecret; 
    } 
    }; 

    void increment(myClass A, int i){ 
     A.topSecret += i; 
    } 

    int main() { 
    myClass x; 
    x.display(); 
    increment(x,10); 
    x.display(); 

    } 
+3

'朋友无效增量( myClass,int);'<< ** void ** – user657267 2015-02-12 09:02:29

+0

是否需要声明返回类型的好友函数? @ user657267 – Bilal 2015-02-12 09:05:30

+0

你应该编写'getter()'和'setter()'函数来访问你的私有成员'topSecret'。 – Aleph0 2015-02-12 09:05:34

回答

2

变化

friend increment(myClass, int); 

friend void increment(myClass &, int); 

这应该解决您的编译错误。


修改传递给函数的原始对象,声明函数取一个参考:

void increment(myClass A, int i){ 

void increment(myClass &A, int i){ 
+0

感谢它,但无效增量功能仍然没有通过它的定义...我的意思是我仍然没有看到递增的值..通过增量(x,10); x.display(); – Bilal 2015-02-12 09:09:37

+0

我编辑了我的代码 – 2015-02-12 09:13:46

2

阿伦的回答显示了如何解决您的编译错误,但这不是你应该如何设计一堂课。定义非会员朋友功能来访问您的内部数据通常会导致维护问题和错误。你会好不声明increment作为公共成员函数,或定义getter和setter方法类:

class myClass{ 
private: 
    int topSecret; 
public: 
    //use initialization list instead of setting in constructor body 
    myClass() : topSecret(100) {} 

    //getter, note the const 
    int GetTopSecret() const { return topSecret; } 
    //setter, non-const 
    void SetTopSecret(int x) { topSecret = x; } 

    //member version 
    void increment (int i) { topSecret += i; } 
}; 

//non-member version with setter 
//note the reference param, you were missing this 
void increment(myClass &A, int i){ 
    A.SetTopSecret(A.GetTopSecret() + i); 
} 
1
  1. 添加无效bebore增量类定义为阿伦A.S说。
  2. ,因为你把对象的值不能更改A.topSecret在递增的功能,所以你只需要改变临时对象,而不是使用无效增量(MyClass的& A,int i)以